address
stringlengths
42
42
source_code
stringlengths
32
1.21M
bytecode
stringlengths
2
49.2k
slither
sequence
0x4116623495a7b406f786c081c402e423cdbfaf73
pragma solidity 0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Snow is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function Snow( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a72305820a0fa7c8e308e5c3b4d42bbd40ddb3a27f6ee301c93c4244bf5c79e4fe60db5100029
[ 38 ]
0x412162b71a193caaff8d6f3a9b94246087356b6d
pragma solidity 0.6.12; 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 Modifier to use in the initializer function of a contract when upgrade EVEN times. */ modifier initializerEven() { require(initializing || isConstructor() || initialized, "Contract instance has already been initialized EVEN times"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = false; } _; 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 Governable is Initializable { address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function initialize(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } modifier governance() { require(msg.sender == governor); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } contract Configurable is Governable { mapping (bytes32 => uint) internal config; function getConfig(bytes32 key) public view returns (uint) { return config[key]; } function getConfig(bytes32 key, uint index) public view returns (uint) { return config[bytes32(uint(key) ^ index)]; } function getConfig(bytes32 key, address addr) public view returns (uint) { return config[bytes32(uint(key) ^ uint(addr))]; } function _setConfig(bytes32 key, uint value) internal { if(config[key] != value) config[key] = value; } function _setConfig(bytes32 key, uint index, uint value) internal { _setConfig(bytes32(uint(key) ^ index), value); } function _setConfig(bytes32 key, address addr, uint value) internal { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } function setConfig(bytes32 key, uint value) external governance { _setConfig(key, value); } function setConfig(bytes32 key, uint index, uint value) external governance { _setConfig(bytes32(uint(key) ^ index), value); } function setConfig(bytes32 key, address addr, uint value) external governance { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } } interface Minter { event Minted(address indexed recipient, address reward_contract, uint minted); function token() external view returns (address); function controller() external view returns (address); function minted(address, address) external view returns (uint); function allowed_to_mint_for(address, address) external view returns (bool); function mint(address gauge) external; function mint_many(address[8] calldata gauges) external; function mint_for(address gauge, address _for) external; function toggle_approve_mint(address minting_user) external; } interface LiquidityGauge { event Deposit(address indexed provider, uint value); event Withdraw(address indexed provider, uint value); event UpdateLiquidityLimit(address user, uint original_balance, uint original_supply, uint working_balance, uint working_supply); function user_checkpoint (address addr) external returns (bool); function claimable_tokens(address addr) external view returns (uint); function claimable_reward(address addr) external view returns (uint); function integrate_checkpoint() external view returns (uint); function kick(address addr) external; function set_approve_deposit(address addr, bool can_deposit) external; function deposit(uint _value) external; function deposit(uint _value, address addr) external; function withdraw(uint _value) external; function withdraw(uint _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function minter() external view returns (address); function crv_token() external view returns (address); function lp_token() external view returns (address); function controller() external view returns (address); function voting_escrow() external view returns (address); function balanceOf(address) external view returns (uint); function totalSupply() external view returns (uint); function future_epoch_time() external view returns (uint); function approved_to_deposit(address, address) external view returns (bool); function working_balances(address) external view returns (uint); function working_supply() external view returns (uint); function period() external view returns (int128); function period_timestamp(uint) external view returns (uint); function integrate_inv_supply(uint) external view returns (uint); function integrate_inv_supply_of(address) external view returns (uint); function integrate_checkpoint_of(address) external view returns (uint); function integrate_fraction(address) external view returns (uint); function inflation_rate() external view returns (uint); function reward_contract() external view returns (address); function rewarded_token() external view returns (address); function reward_integral() external view returns (uint); function reward_integral_for(address) external view returns (uint); function rewards_for(address) external view returns (uint); function claimed_rewards_for(address) external view returns (uint); } contract SSimpleGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; uint override public reward_integral; mapping(address => uint) override public reward_integral_for; mapping(address => uint) override public rewards_for; mapping(address => uint) override public claimed_rewards_for; uint public span; uint public end; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[addr] = balanceOf[addr].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(addr, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool claim_rewards) virtual override public { _checkpoint(msg.sender, claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address) virtual override public view returns (uint) { return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = SMinter(minter).quotas(address(this)); amount = amount.mul(balanceOf[addr]).div(totalSupply); uint lasttime = integrate_checkpoint_of[addr]; if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); address teamAddr = address(config['teamAddr']); uint teamRatio = config['teamRatio']; if(teamAddr != address(0) && teamRatio != 0) integrate_fraction[teamAddr] = integrate_fraction[teamAddr].add(amount.mul(teamRatio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { uint amount = claimable_tokens(addr); _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); integrate_checkpoint_of[addr] = now; } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return now; } } c SExactGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; bytes32 internal constant _devAddr_ = 'devAddr'; bytes32 internal constant _devRatio_ = 'devRatio'; bytes32 internal constant _ecoAddr_ = 'ecoAddr'; bytes32 internal constant _ecoRatio_ = 'ecoRatio'; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; uint override public reward_integral; mapping(address => uint) override public reward_integral_for; mapping(address => uint) internal rewards_for_; // obsolete mapping(address => uint) internal claimed_rewards_for_; // obsoleted uint public span; uint public end; mapping(address => uint) public sumMiningPerOf; uint public sumMiningPer; uint public bufReward; uint public lasttime; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; lasttime = now; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(msg.sender, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool _claim_rewards) virtual override public { _checkpoint(msg.sender, _claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address addr) virtual override public view returns (uint) { addr; return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint) { return _claimable_tokens(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr]); } function _claimable_tokens(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = sumPer.sub(lastSumPer); amount = amount.add(delta.mul(1 ether).div(totalSupply)); amount = amount.mul(balanceOf[addr]).div(1 ether); } function claimableDelta() virtual internal view returns(uint amount) { amount = SMinter(minter).quotas(address(this)).sub(bufReward); if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); addr = address(config[_devAddr_]); uint ratio = config[_devRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); addr = address(config[_ecoAddr_]); ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { if(span == 0 || totalSupply == 0) return; uint delta = claimableDelta(); uint amount = _claimable_tokens(addr, delta, sumMiningPer, sumMiningPerOf[addr]); if(delta != amount) bufReward = bufReward.add(delta).sub(amount); if(delta > 0) sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(totalSupply)); if(sumMiningPerOf[addr] != sumMiningPer) sumMiningPerOf[addr] = sumMiningPer; lasttime = now; _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return lasttime; } function rewards_for(address) virtual override external view returns (uint) { return 0; } function claimed_rewards_for(address) virtual override external view returns (uint) { return 0; } } contra uge is SExactGauge { address[] public rewards; mapping(address => mapping(address =>uint)) public sumRewardPerOf; // recipient => rewarded_token => can sumRewardPerOf mapping(address => uint) public sumRewardPer; // rewarded_token => can sumRewardPerOf function initialize(address governor, address _minter, address _lp_token, address _nestGauge, address[] memory _moreRewards) public initializer { super.initialize(governor, _minter, _lp_token); reward_contract = _nestGauge; rewarded_token = LiquidityGauge(_nestGauge).crv_token(); rewards = _moreRewards; rewards.push(rewarded_token); address rewarded_token2 = LiquidityGauge(_nestGauge).rewarded_token(); if(rewarded_token2 != address(0)) rewards.push(rewarded_token2); LiquidityGauge(_nestGauge).integrate_checkpoint(); // just check for(uint i=0; i<_moreRewards.length; i++) IERC20(_moreRewards[i]).totalSupply(); // just check } function _deposit(address from, uint amount) virtual override internal { super._deposit(from, amount); // lp_token.safeTransferFrom(from, address(this), amount); lp_token.safeApprove(reward_contract, amount); LiquidityGauge(reward_contract).deposit(amount); } function _withdraw(address to, uint amount) virtual override internal { LiquidityGauge(reward_contract).withdraw(amount); super._withdraw(to, amount); // lp_token.safeTransfer(to, amount); } function claim_rewards(address to) virtual override public { if(span == 0 || totalSupply == 0) return; uint[] memory bals = new uint[](rewards.length); for(uint i=0; i<bals.length; i++) bals[i] = IERC20(rewards[i]).balanceOf(address(this)); Minter(LiquidityGauge(reward_contract).minter()).mint(reward_contract); LiquidityGauge(reward_contract).claim_rewards(); for(uint i=0; i<bals.length; i++) { uint delta = IERC20(rewards[i]).balanceOf(address(this)).sub(bals[i]); uint amount = _claimable_tokens(msg.sender, delta, sumRewardPer[rewards[i]], sumRewardPerOf[msg.sender][rewards[i]]); if(delta > 0) sumRewardPer[rewards[i]] = sumRewardPer[rewards[i]].add(delta.mul(1 ether).div(totalSupply)); if(sumRewardPerOf[msg.sender][rewards[i]] != sumRewardPer[rewards[i]]) sumRewardPerOf[msg.sender][rewards[i]] = sumRewardPer[rewards[i]]; if(amount > 0) rewards[i].safeTransfer(to, amount); } } function claimable_reward(address addr) virtual override public view returns (uint) { //uint delta = LiquidityGauge(reward_contract).claimable_tokens(address(this)); // Error: Mutable call in static context uint delta = LiquidityGauge(reward_contract).integrate_fraction(address(this)).sub(Minter(LiquidityGauge(reward_contract).minter()).minted(address(this), reward_contract)); return _claimable_tokens(addr, delta, sumRewardPer[rewarded_token], sumRewardPerOf[addr][rewarded_token]); } function claimable_reward2(address addr) virtual public view returns (uint) { uint delta = LiquidityGauge(reward_contract).claimable_reward(address(this)); address reward2 = LiquidityGauge(reward_contract).rewarded_token(); return _claimable_tokens(addr, delta, sumRewardPer[reward2], sumRewardPerOf[addr][reward2]); } function claimable_reward(address addr, address reward) virtual public view returns (uint) { return _claimable_tokens(addr, 0, sumRewardPer[reward], sumRewardPerOf[addr][reward]); } function claimed_rewards_for(address addr, address reward) virtual public view returns (uint) { return _claimable_tokens(addr, 0, sumRewardPerOf[addr][reward], 0); } function claimed_rewards_for(address addr) virtual override public view returns (uint) { return claimed_rewards_for(addr, rewarded_token); } function claimed_rewards_for2(address addr) virtual public view returns (uint) { return claimed_rewards_for(addr, LiquidityGauge(reward_contract).rewarded_token()); } function rewards_for(address addr, address reward) virtual public view returns (uint) { return _claimable_tokens(addr, 0, sumRewardPer[reward], 0); } function rewards_for(address addr) virtual override public view returns (uint) { return rewards_for(addr, rewarded_token); } function rewards_for2(address addr) virtual public view returns (uint) { return rewards_for(addr, LiquidityGauge(reward_contract).rewarded_token()); } } contrac is Minter, Configurable { using SafeMath for uint; using Address for address payable; using TransferHelper for address; bytes32 internal constant _allowContract_ = 'allowContract'; bytes32 internal constant _allowlist_ = 'allowlist'; bytes32 internal constant _blocklist_ = 'blocklist'; address override public token; address override public controller; mapping(address => mapping(address => uint)) override public minted; // user => reward_contract => value mapping(address => mapping(address => bool)) override public allowed_to_mint_for; // minter => user => can mint? mapping(address => uint) public quotas; // reward_contract => quota; function initialize(address governor, address token_) public initializer { super.initialize(governor); token = token_; } function setGaugeQuota(address gauge, uint quota) public governance { quotas[gauge] = quota; } function mint(address gauge) virtual override public { mint_for(gauge, msg.sender); } function mint_many(address[8] calldata gauges) virtual override external { for(uint i=0; i<gauges.length; i++) mint(gauges[i]); } function mint_for(address gauge, address _for) virtual override public { require(_for == msg.sender || allowed_to_mint_for[msg.sender][_for], 'Not approved'); require(quotas[gauge] > 0, 'No quota'); require(getConfig(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfig(_allowlist_, msg.sender) != 0, 'No allowContract'); LiquidityGauge(gauge).user_checkpoint(_for); uint total_mint = LiquidityGauge(gauge).integrate_fraction(_for); uint to_mint = total_mint.sub(minted[_for][gauge]); if(to_mint != 0) { quotas[gauge] = quotas[gauge].sub(to_mint); token.safeTransfer(_for, to_mint); minted[_for][gauge] = total_mint; emit Minted(_for, gauge, total_mint); } } function toggle_approve_mint(address minting_user) virtual override external { allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[minting_user][msg.sender]; } } /* // he 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; } } 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; } function sqrt(uint x)public pure returns(uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } 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); } } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) public _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 public _totalSupply; string internal _name; string internal _symbol; 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) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract SfgToken is ERC20 { constructor(address SfgFarm) ERC20("Stable Finance Governance Token", "SFG") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfgFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } contract SfyToken is ERC20 { constructor(address SfyFarm) ERC20("Stable Finance Yield Token", "SFY") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfyFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
0x608060405234801561001057600080fd5b506004361061035d5760003560e01c806381c0c263116101d3578063c0c53b8b11610104578063e1522536116100a2578063efbe1c1c1161007c578063efbe1c1c146108c4578063f77c4791146108cc578063fd96044b146106ff578063fec8ee0c146108d45761035d565b8063e15225361461086f578063e6f1daf21461089d578063ef78d4fd146108a55761035d565b8063d31f3f6d116100de578063d31f3f6d14610810578063ddf2be3f14610818578063de263bfa14610841578063dfe05031146108675761035d565b8063c0c53b8b146107b2578063c4d66de8146107ea578063d2797b59146106ff5761035d565b80639df4ed5611610171578063b6aa515b1161014b578063b6aa515b1461075f578063b6b55f2514610785578063be5d1be9146107a2578063bf88a6ff146107aa5761035d565b80639df4ed56146106ff578063aaa626b614610725578063b21544f31461072d5761035d565b806387564d84116101ad57806387564d841461066b5780638ec872e31461069057806396c55175146106b35780639bd324f2146106d95761035d565b806381c0c2631461063557806382c630661461063d57806384e9bd7e146106455761035d565b80632585581f116102ad57806352665f471161024b5780636e553f65116102255780636e553f65146105be57806370a08231146105ea5780637598108c1461061057806376d8b1171461062d5761035d565b806352665f471461056d57806365fe9451146105995780636dd5b69d146105a15761035d565b806338d074361161028757806338d07436146104fe5780633ccfd60b1461052357806343d7f86f1461052b5780634b820093146105335761035d565b80632585581f146104b35780632e1a7d4d146104bb57806333134583146104d85761035d565b806316fa50b11161031a57806318160ddd116102f457806318160ddd1461044f5780631b9f546f146104575780631d2747d41461047d57806323a58292146104ab5761035d565b806316fa50b11461043757806317e280891461043f578063180692d0146104475761035d565b8063075461721461036257806309400707146103865780630c340a24146103be57806313ecb1ca146103c657806313fa1368146103ec57806315fe96dc14610412575b600080fd5b61036a6108f1565b604080516001600160a01b039092168252519081900360200190f35b6103ac6004803603602081101561039c57600080fd5b50356001600160a01b0316610900565b60408051918252519081900360200190f35b61036a61091e565b6103ac600480360360208110156103dc57600080fd5b50356001600160a01b031661092d565b6103ac6004803603602081101561040257600080fd5b50356001600160a01b031661093f565b6104356004803603604081101561042857600080fd5b508035906020013561095d565b005b61036a610982565b6103ac61099d565b6103ac6109a3565b6103ac6109b5565b6103ac6004803603602081101561046d57600080fd5b50356001600160a01b03166109bb565b6104356004803603604081101561049357600080fd5b506001600160a01b03813516906020013515156109d9565b6103ac610a0f565b6103ac610a21565b610435600480360360208110156104d157600080fd5b5035610a33565b6103ac600480360360208110156104ee57600080fd5b50356001600160a01b0316610a41565b6104356004803603604081101561051457600080fd5b50803590602001351515610a8e565b610435610b19565b6103ac610b36565b6105596004803603602081101561054957600080fd5b50356001600160a01b0316610b48565b604080519115158252519081900360200190f35b6103ac6004803603604081101561058357600080fd5b50803590602001356001600160a01b0316610b5d565b6103ac610b79565b6103ac600480360360208110156105b757600080fd5b5035610b8b565b610435600480360360408110156105d457600080fd5b50803590602001356001600160a01b0316610b9d565b6103ac6004803603602081101561060057600080fd5b50356001600160a01b0316610ca0565b6103ac6004803603602081101561062657600080fd5b5035610cb2565b61036a610cd2565b610435610ce1565b61036a610d42565b6104356004803603602081101561065b57600080fd5b50356001600160a01b0316610a3e565b6104356004803603604081101561068157600080fd5b50803590602001351515610d51565b6103ac600480360360408110156106a657600080fd5b5080359060200135610dbc565b610435600480360360208110156106c957600080fd5b50356001600160a01b0316610dcf565b6103ac600480360360208110156106ef57600080fd5b50356001600160a01b0316610dda565b6103ac6004803603602081101561071557600080fd5b50356001600160a01b0316610df8565b6103ac610dfe565b6104356004803603606081101561074357600080fd5b508035906001600160a01b036020820135169060400135610e10565b6104356004803603602081101561077557600080fd5b50356001600160a01b0316610e41565b6104356004803603602081101561079b57600080fd5b5035610e61565b6103ac610e6b565b61036a610e71565b610435600480360360608110156107c857600080fd5b506001600160a01b038135811691602081013582169160409091013516610e8c565b6104356004803603602081101561080057600080fd5b50356001600160a01b031661104e565b6103ac61113f565b6104356004803603606081101561082e57600080fd5b5080359060208101359060400135611152565b6103ac6004803603602081101561085757600080fd5b50356001600160a01b0316611175565b61036a611193565b6105596004803603604081101561088557600080fd5b506001600160a01b03813581169160200135166111a2565b6104356111c2565b6108ad6111cb565b60408051600f9290920b8252519081900360200190f35b6103ac6111d4565b61036a6111e6565b6103ac600480360360208110156108ea57600080fd5b50356111f5565b6035546001600160a01b031681565b6c02863c1f5cdae42f95400000436020526000908152604090205481565b6033546001600160a01b031681565b603e6020526000908152604090205481565b6c02863c1f5cdae42f95400000486020526000908152604090205481565b6033546001600160a01b0316331461097457600080fd5b61097e828261121a565b5050565b6c02863c1f5cdae42f9540000046546001600160a01b031681565b603f5481565b6c02863c1f5cdae42f95400000445481565b603b5481565b6c02863c1f5cdae42f954000004d6020526000908152604090205481565b6001600160a01b03919091166000908152603d602090815260408083203384529091529020805460ff1916911515919091179055565b6c02863c1f5cdae42f95400000505481565b6c02863c1f5cdae42f954000004b5481565b610a3e816001610a8e565b50565b6000610a8882610a4f611241565b6c02863c1f5cdae42f954000004e546001600160a01b03861660009081526c02863c1f5cdae42f954000004d60205260409020546113fe565b92915050565b610a9833826114a1565b603b54610aa5908361163d565b603b55336000908152603a6020526040902054610ac2908361163d565b336000818152603a6020526040902091909155610adf9083611686565b60408051838152905133917f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364919081900360200190a25050565b336000908152603a6020526040902054610b34906001610a8e565b565b6c02863c1f5cdae42f954000004f5481565b6000610b558260016114a1565b506001919050565b6001600160a01b03161860009081526034602052604090205490565b6c02863c1f5cdae42f954000004e5481565b60009081526034602052604090205490565b6001600160a01b038116331480610bd75750336000908152603d602090815260408083206001600160a01b038516845290915290205460ff165b610c17576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b610c228160016114a1565b610c2c818361169d565b336000908152603a6020526040902054610c4690836116b5565b336000908152603a6020526040902055603b54610c6390836116b5565b603b5560408051838152905133917fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c919081900360200190a25050565b603a6020526000908152604090205481565b6041816c01431e0fae6d7217caa00000008110610ccb57fe5b0154905081565b6036546001600160a01b031681565b6033546001600160a01b03163314610cf857600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b6037546001600160a01b031681565b6033546001600160a01b03163314610d6857600080fd5b6c02863c1f5cdae42f954000004b8290558015610d96574282016c02863c1f5cdae42f954000004c55610da8565b60006c02863c1f5cdae42f954000004c555b5050426c02863c1f5cdae42f954000005055565b1860009081526034602052604090205490565b610a3e8160016114a1565b6c02863c1f5cdae42f95400000426020526000908152604090205481565b50600090565b6c02863c1f5cdae42f95400000475481565b6033546001600160a01b03163314610e2757600080fd5b610e3c6001600160a01b03831684188261121a565b505050565b6033546001600160a01b03163314610e5857600080fd5b610a3e8161170f565b610a3e8133610b9d565b603c5481565b6c02863c1f5cdae42f9540000045546001600160a01b031681565b600054610100900460ff1680610ea55750610ea561177e565b80610eb3575060005460ff16155b610eee5760405162461bcd60e51b815260040180806020018281038252602e815260200180611df7602e913960400191505060405180910390fd5b600054610100900460ff16158015610f19576000805460ff1961ff0019909116610100171660011790555b610f228461104e565b603580546001600160a01b0319166001600160a01b03851690811790915560408051637e062a3560e11b8152905163fc0c546a91600480820192602092909190829003018186803b158015610f7657600080fd5b505afa158015610f8a573d6000803e3d6000fd5b505050506040513d6020811015610fa057600080fd5b5051603680546001600160a01b03199081166001600160a01b0393841617909155603780549091168483161790819055604080516318160ddd60e01b8152905191909216916318160ddd916004808301926020929190829003018186803b15801561100a57600080fd5b505afa15801561101e573d6000803e3d6000fd5b505050506040513d602081101561103457600080fd5b50508015611048576000805461ff00191690555b50505050565b600054610100900460ff1680611067575061106761177e565b80611075575060005460ff16155b6110b05760405162461bcd60e51b815260040180806020018281038252602e815260200180611df7602e913960400191505060405180910390fd5b600054610100900460ff161580156110db576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a3801561097e576000805461ff00191690555050565b6c02863c1f5cdae42f9540000050545b90565b6033546001600160a01b0316331461116957600080fd5b610e3c8383188261121a565b6c02863c1f5cdae42f95400000416020526000908152604090205481565b6039546001600160a01b031681565b603d60209081526000928352604080842090915290825290205460ff1681565b610b3433610a3e565b604054600f0b81565b6c02863c1f5cdae42f954000004c5481565b6038546001600160a01b031681565b6c01431e0fae6d7217caa0000041816c01431e0fae6d7217caa00000008110610ccb57fe5b600082815260346020526040902054811461097e5760009182526034602052604090912055565b6c02863c1f5cdae42f954000004f546035546040805163c33342e960e01b815230600482015290516000936112d69390926001600160a01b039091169163c33342e991602480820192602092909190829003018186803b1580156112a457600080fd5b505afa1580156112b8573d6000803e3d6000fd5b505050506040513d60208110156112ce57600080fd5b50519061163d565b90506c02863c1f5cdae42f954000004c5460001415611369576c02863c1f5cdae42f954000004b546c02863c1f5cdae42f95400000505461131890429061163d565b1015611364576113616c02863c1f5cdae42f954000004b5461135b6113546c02863c1f5cdae42f9540000050544261163d90919063ffffffff16565b8490611784565b906117dd565b90505b61114f565b6c02863c1f5cdae42f954000004c544210156113d5576113616113b16c02863c1f5cdae42f9540000050546c02863c1f5cdae42f954000004c5461163d90919063ffffffff16565b61135b6113546c02863c1f5cdae42f9540000050544261163d90919063ffffffff16565b6c02863c1f5cdae42f954000004c546c02863c1f5cdae42f9540000050541061114f5750600090565b60006c02863c1f5cdae42f954000004b546000148061141d5750603b54155b1561142a57506000611499565b611434838361163d565b905061146161145a603b5461135b670de0b6b3a76400008861178490919063ffffffff16565b82906116b5565b6001600160a01b0386166000908152603a602052604090205490915061149690670de0b6b3a76400009061135b908490611784565b90505b949350505050565b6c02863c1f5cdae42f954000004b5415806114bc5750603b54155b156114c65761097e565b60006114d0611241565b9050600061151f84836c02863c1f5cdae42f954000004e546c02863c1f5cdae42f954000004d6000896001600160a01b03166001600160a01b03168152602001908152602001600020546113fe565b9050808214611563576115538161154d846c02863c1f5cdae42f954000004f546116b590919063ffffffff16565b9061163d565b6c02863c1f5cdae42f954000004f555b81156115ab57603b5461159b906115869061135b85670de0b6b3a7640000611784565b6c02863c1f5cdae42f954000004e54906116b5565b6c02863c1f5cdae42f954000004e555b6c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d602052604090205414611619576c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020555b426c02863c1f5cdae42f954000005055611633848261181f565b611048848461097e565b600061167f83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611a12565b9392505050565b60375461097e906001600160a01b03168383611aa9565b60375461097e906001600160a01b0316833084611c13565b60008282018381101561167f576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6001600160a01b03811661172257600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b303b1590565b60008261179357506000610a88565b828202828482816117a057fe5b041461167f5760405162461bcd60e51b8152600401808060200182810382526021815260200180611dd66021913960400191505060405180910390fd5b600061167f83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611d70565b801561097e576001600160a01b03821660009081526c02863c1f5cdae42f9540000043602052604090205461185490826116b5565b6001600160a01b0392831660009081526c02863c1f5cdae42f95400000436020908152604082209290925560349091527fe9b68ca2b566af5bdfbb3361c12fcbb5dbf956c250bbd74cc175cc06ec62c7915467646576526174696f60c01b9091527fb8fbd2e70438ec482a0e7fc9b87580647182c1694aea1065027a1d634e92d6b95490928316158015906118e857508015155b1561195757611931611906670de0b6b3a764000061135b8585611784565b6001600160a01b03851660009081526c02863c1f5cdae42f95400000436020526040902054906116b5565b6001600160a01b03841660009081526c02863c1f5cdae42f954000004360205260409020555b5060346020527f82e0b58992d24d827851dcbd63485b5933f9d3ae4c2ca50477d1437e73f6d342546765636f526174696f60c01b6000527ffc6561c6b7742261fbeab673eba1bedd2f5b1d7221f757ea8c9a87d664cfbed2549092506001600160a01b038316158015906119ca57508015155b15610e3c576119e8611906670de0b6b3a764000061135b8585611784565b6001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902055505050565b60008184841115611aa15760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611a66578181015183820152602001611a4e565b50505050905090810190601f168015611a935780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b60208310611b265780518252601f199092019160209182019101611b07565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611b88576040519150601f19603f3d011682016040523d82523d6000602084013e611b8d565b606091505b5091509150818015611bbb575080511580611bbb5750808060200190516020811015611bb857600080fd5b50515b611c0c576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b5050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17815292518251600094606094938a169392918291908083835b60208310611c985780518252601f199092019160209182019101611c79565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611cfa576040519150601f19603f3d011682016040523d82523d6000602084013e611cff565b606091505b5091509150818015611d2d575080511580611d2d5750808060200190516020811015611d2a57600080fd5b50515b611d685760405162461bcd60e51b8152600401808060200182810382526024815260200180611e256024913960400191505060405180910390fd5b505050505050565b60008183611dbf5760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315611a66578181015183820152602001611a4e565b506000838581611dcb57fe5b049594505050505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c4544a264697066735822122085a474763576b02ab44aa1bfe6d4510f69d04facda02ef4ab7c7c5ade0396ba264736f6c634300060c0033
[ 5, 4, 9, 7 ]
0x41517D4102Cc6ddB4f6daCf19284E6CA54aad0AB
pragma solidity 0.6.12; 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 Modifier to use in the initializer function of a contract when upgrade EVEN times. */ modifier initializerEven() { require(initializing || isConstructor() || initialized, "Contract instance has already been initialized EVEN times"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = false; } _; 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 Governable is Initializable { address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function initialize(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } modifier governance() { require(msg.sender == governor); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } contract Configurable is Governable { mapping (bytes32 => uint) internal config; function getConfig(bytes32 key) public view returns (uint) { return config[key]; } function getConfig(bytes32 key, uint index) public view returns (uint) { return config[bytes32(uint(key) ^ index)]; } function getConfig(bytes32 key, address addr) public view returns (uint) { return config[bytes32(uint(key) ^ uint(addr))]; } function _setConfig(bytes32 key, uint value) internal { if(config[key] != value) config[key] = value; } function _setConfig(bytes32 key, uint index, uint value) internal { _setConfig(bytes32(uint(key) ^ index), value); } function _setConfig(bytes32 key, address addr, uint value) internal { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } function setConfig(bytes32 key, uint value) external governance { _setConfig(key, value); } function setConfig(bytes32 key, uint index, uint value) external governance { _setConfig(bytes32(uint(key) ^ index), value); } function setConfig(bytes32 key, address addr, uint value) external governance { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } } interface Minter { event Minted(address indexed recipient, address reward_contract, uint minted); function token() external view returns (address); function controller() external view returns (address); function minted(address, address) external view returns (uint); function allowed_to_mint_for(address, address) external view returns (bool); function mint(address gauge) external; function mint_many(address[8] calldata gauges) external; function mint_for(address gauge, address _for) external; function toggle_approve_mint(address minting_user) external; } interface LiquidityGauge { event Deposit(address indexed provider, uint value); event Withdraw(address indexed provider, uint value); event UpdateLiquidityLimit(address user, uint original_balance, uint original_supply, uint working_balance, uint working_supply); function user_checkpoint (address addr) external returns (bool); function claimable_tokens(address addr) external view returns (uint); function claimable_reward(address addr) external view returns (uint); function integrate_checkpoint() external view returns (uint); function kick(address addr) external; function set_approve_deposit(address addr, bool can_deposit) external; function deposit(uint _value) external; function deposit(uint _value, address addr) external; function withdraw(uint _value) external; function withdraw(uint _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function minter() external view returns (address); function crv_token() external view returns (address); function lp_token() external view returns (address); function controller() external view returns (address); function voting_escrow() external view returns (address); function balanceOf(address) external view returns (uint); function totalSupply() external view returns (uint); function future_epoch_time() external view returns (uint); function approved_to_deposit(address, address) external view returns (bool); function working_balances(address) external view returns (uint); function working_supply() external view returns (uint); function period() external view returns (int128); function period_timestamp(uint) external view returns (uint); function integrate_inv_supply(uint) external view returns (uint); function integrate_inv_supply_of(address) external view returns (uint); function integrate_checkpoint_of(address) external view returns (uint); function integrate_fraction(address) external view returns (uint); function inflation_rate() external view returns (uint); function reward_contract() external view returns (address); function rewarded_token() external view returns (address); function reward_integral() external view returns (uint); function reward_integral_for(address) external view returns (uint); function rewards_for(address) external view returns (uint); function claimed_rewards_for(address) external view returns (uint); } contract SSimpleGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; uint override public reward_integral; mapping(address => uint) override public reward_integral_for; mapping(address => uint) override public rewards_for; mapping(address => uint) override public claimed_rewards_for; uint public span; uint public end; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[addr] = balanceOf[addr].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(addr, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool claim_rewards) virtual override public { _checkpoint(msg.sender, claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address) virtual override public view returns (uint) { return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = SMinter(minter).quotas(address(this)); amount = amount.mul(balanceOf[addr]).div(totalSupply); uint lasttime = integrate_checkpoint_of[addr]; if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); address teamAddr = address(config['teamAddr']); uint teamRatio = config['teamRatio']; if(teamAddr != address(0) && teamRatio != 0) integrate_fraction[teamAddr] = integrate_fraction[teamAddr].add(amount.mul(teamRatio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { uint amount = claimable_tokens(addr); _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); integrate_checkpoint_of[addr] = now; } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return now; } } c SExactGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; bytes32 internal constant _devAddr_ = 'devAddr'; bytes32 internal constant _devRatio_ = 'devRatio'; bytes32 internal constant _ecoAddr_ = 'ecoAddr'; bytes32 internal constant _ecoRatio_ = 'ecoRatio'; bytes32 internal constant _claim_rewards_ = 'claim_rewards'; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; mapping(address => uint) public reward_integral_; // rewarded_token => reward_integral mapping(address => mapping(address => uint)) public reward_integral_for_; // recipient => rewarded_token => reward_integral_for mapping(address => mapping(address => uint)) public rewards_for_; mapping(address => mapping(address => uint)) public claimed_rewards_for_; uint public span; uint public end; mapping(address => uint) public sumMiningPerOf; uint public sumMiningPer; uint public bufReward; uint public lasttime; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; if(lasttime == 0) lasttime = now; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, config[_claim_rewards_] == 0 ? false : true); _deposit(addr, amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(msg.sender, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender]); } function withdraw(uint amount) virtual override public { withdraw(amount, config[_claim_rewards_] == 0 ? false : true); } function withdraw(uint amount, bool _claim_rewards) virtual override public { _checkpoint(msg.sender, _claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address addr) virtual override public view returns (uint) { addr; return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint r) { r = integrate_fraction[addr].sub(Minter(minter).minted(addr, address(this))); r = r.add(_claimable_last(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr])); } function _claimable_last(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = sumPer.sub(lastSumPer); amount = amount.add(delta.mul(1 ether).div(totalSupply)); amount = amount.mul(balanceOf[addr]).div(1 ether); } function claimableDelta() virtual internal view returns(uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = SMinter(minter).quotas(address(this)).sub(bufReward); if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); addr = address(config[_devAddr_]); uint ratio = config[_devRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); addr = address(config[_ecoAddr_]); ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { if(span == 0 || totalSupply == 0) return; uint delta = claimableDelta(); uint amount = _claimable_last(addr, delta, sumMiningPer, sumMiningPerOf[addr]); if(delta != amount) bufReward = bufReward.add(delta).sub(amount); if(delta > 0) sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(totalSupply)); if(sumMiningPerOf[addr] != sumMiningPer) sumMiningPerOf[addr] = sumMiningPer; lasttime = now; _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, config[_claim_rewards_] == 0 ? false : true); return true; } function integrate_checkpoint() override external view returns (uint) { return lasttime; } function reward_integral() virtual override external view returns (uint) { return reward_integral_[rewarded_token]; } function reward_integral_for(address addr) virtual override external view returns (uint) { return reward_integral_for_[addr][rewarded_token]; } function rewards_for(address addr) virtual override external view returns (uint) { return rewards_for_[addr][rewarded_token]; } function claimed_rewards_for(address addr) virtual override external view returns (uint) { return claimed_rewards_for_[addr][rewarded_token]; } } contra uge is SExactGauge { address[] public rewards; //mapping(address => mapping(address =>uint)) internal sumRewardPerOf_; // recipient => rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_ //mapping(address => uint) internal sumRewardPer_; // rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_for_ function initialize(address governor, address _minter, address _lp_token, address _nestGauge, address[] memory _moreRewards) public initializer { super.initialize(governor, _minter, _lp_token); reward_contract = _nestGauge; rewarded_token = LiquidityGauge(_nestGauge).crv_token(); rewards = _moreRewards; rewards.push(rewarded_token); address rewarded_token2 = LiquidityGauge(_nestGauge).rewarded_token(); if(rewarded_token2 != address(0)) rewards.push(rewarded_token2); LiquidityGauge(_nestGauge).integrate_checkpoint(); // just check for(uint i=0; i<_moreRewards.length; i++) IERC20(_moreRewards[i]).totalSupply(); // just check } function _deposit(address from, uint amount) virtual override internal { super._deposit(from, amount); // lp_token.safeTransferFrom(from, address(this), amount); lp_token.safeApprove(reward_contract, amount); LiquidityGauge(reward_contract).deposit(amount); } function _withdraw(address to, uint amount) virtual override internal { LiquidityGauge(reward_contract).withdraw(amount); super._withdraw(to, amount); // lp_token.safeTransfer(to, amount); } function claim_rewards(address to) virtual override public { if(span == 0 || totalSupply == 0) return; _checkpoint_rewards(to, true); for(uint i=0; i<rewards.length; i++) { uint amount = rewards_for_[to][rewards[i]].sub(claimed_rewards_for_[to][rewards[i]]); if(amount > 0) { rewards[i].safeTransfer(to, amount); claimed_rewards_for_[to][rewards[i]] = rewards_for_[to][rewards[i]]; } } } function _checkpoint_rewards(address addr, bool _claim_rewards) virtual override internal { if(span == 0 || totalSupply == 0) return; uint[] memory drs = new uint[](rewards.length); if(_claim_rewards) { for(uint i=0; i<drs.length; i++) drs[i] = IERC20(rewards[i]).balanceOf(address(this)); Minter(LiquidityGauge(reward_contract).minter()).mint(reward_contract); LiquidityGauge(reward_contract).claim_rewards(); for(uint i=0; i<drs.length; i++) drs[i] = IERC20(rewards[i]).balanceOf(address(this)).sub(drs[i]); } for(uint i=0; i<drs.length; i++) { uint amount = _claimable_last(addr, drs[i], reward_integral_[rewards[i]], reward_integral_for_[addr][rewards[i]]); if(amount > 0) rewards_for_[addr][rewards[i]] = rewards_for_[addr][rewards[i]].add(amount); if(drs[i] > 0) reward_integral_[rewards[i]] = reward_integral_[rewards[i]].add(drs[i].mul(1 ether).div(totalSupply)); if(reward_integral_for_[addr][rewards[i]] != reward_integral_[rewards[i]]) reward_integral_for_[addr][rewards[i]] = reward_integral_[rewards[i]]; } } function claimable_reward(address addr) virtual override public view returns (uint r) { //uint delta = LiquidityGauge(reward_contract).claimable_tokens(address(this)); // Error: Mutable call in static context uint delta = LiquidityGauge(reward_contract).integrate_fraction(address(this)).sub(Minter(LiquidityGauge(reward_contract).minter()).minted(address(this), reward_contract)); r = _claimable_last(addr, delta, reward_integral_[rewarded_token], reward_integral_for_[addr][rewarded_token]); r = r.add(rewards_for_[addr][rewarded_token].sub(claimed_rewards_for_[addr][rewarded_token])); } function claimable_reward2(address addr) virtual public view returns (uint r) { uint delta = LiquidityGauge(reward_contract).claimable_reward(address(this)); address reward2 = LiquidityGauge(reward_contract).rewarded_token(); r = _claimable_last(addr, delta, reward_integral_[reward2], reward_integral_for_[addr][reward2]); r = r.add(rewards_for_[addr][reward2].sub(claimed_rewards_for_[addr][reward2])); } function claimable_reward(address addr, address reward) virtual public view returns (uint r) { r = _claimable_last(addr, 0, reward_integral_[reward], reward_integral_for_[addr][reward]); r = r.add(rewards_for_[addr][reward].sub(claimed_rewards_for_[addr][reward])); } function claimed_rewards_for2(address addr) virtual public view returns (uint) { return claimed_rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()]; } function rewards_for2(address addr) virtual public view returns (uint) { return rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()]; } } contrac is Minter, Configurable { using SafeMath for uint; using Address for address payable; using TransferHelper for address; bytes32 internal constant _allowContract_ = 'allowContract'; bytes32 internal constant _allowlist_ = 'allowlist'; bytes32 internal constant _blocklist_ = 'blocklist'; address override public token; address override public controller; mapping(address => mapping(address => uint)) override public minted; // user => reward_contract => value mapping(address => mapping(address => bool)) override public allowed_to_mint_for; // minter => user => can mint? mapping(address => uint) public quotas; // reward_contract => quota; function initialize(address governor, address token_) public initializer { super.initialize(governor); token = token_; } function setGaugeQuota(address gauge, uint quota) public governance { quotas[gauge] = quota; } function mint(address gauge) virtual override public { mint_for(gauge, msg.sender); } function mint_many(address[8] calldata gauges) virtual override external { for(uint i=0; i<gauges.length; i++) mint(gauges[i]); } function mint_many(address[] calldata gauges) virtual external { for(uint i=0; i<gauges.length; i++) mint(gauges[i]); } function mint_for(address gauge, address _for) virtual override public { require(_for == msg.sender || allowed_to_mint_for[msg.sender][_for], 'Not approved'); require(quotas[gauge] > 0, 'No quota'); require(getConfig(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfig(_allowlist_, msg.sender) != 0, 'No allowContract'); LiquidityGauge(gauge).user_checkpoint(_for); uint total_mint = LiquidityGauge(gauge).integrate_fraction(_for); uint to_mint = total_mint.sub(minted[_for][gauge]); if(to_mint != 0) { quotas[gauge] = quotas[gauge].sub(to_mint); token.safeTransfer(_for, to_mint); minted[_for][gauge] = total_mint; emit Minted(_for, gauge, total_mint); } } function toggle_approve_mint(address minting_user) virtual override external { allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[minting_user][msg.sender]; } } /* // he 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; } } 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; } function sqrt(uint x)public pure returns(uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } 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); } } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) public _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 public _totalSupply; string internal _name; string internal _symbol; 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) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract SfgToken is ERC20 { constructor(address SfgFarm) ERC20("Stable Finance Governance Token", "SFG") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfgFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } contract SfyToken is ERC20 { constructor(address SfyFarm) ERC20("Stable Finance Yield Token", "SFY") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfyFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
0x608060405234801561001057600080fd5b50600436106103db5760003560e01c806376d8b1171161020a578063c0c53b8b11610125578063e1522536116100b8578063f301af4211610087578063f301af4214610ac0578063f77c479114610add578063f8453e7c14610ae5578063fd96044b14610bb0578063fec8ee0c14610bd6576103db565b8063e152253614610a63578063e6f1daf214610a91578063ef78d4fd14610a99578063efbe1c1c14610ab8576103db565b8063d31f3f6d116100f4578063d31f3f6d14610a04578063ddf2be3f14610a0c578063de263bfa14610a35578063dfe0503114610a5b576103db565b8063c0c53b8b1461095a578063c4d66de814610992578063cdf10baf146109b8578063d2797b59146109de576103db565b80639bd324f21161019d578063b6aa515b1161016c578063b6aa515b14610907578063b6b55f251461092d578063be5d1be91461094a578063bf88a6ff14610952576103db565b80639bd324f2146108815780639df4ed56146108a7578063aaa626b6146108cd578063b21544f3146108d5576103db565b806387564d84116101d957806387564d84146107e55780638ec872e31461080a57806396c551751461082d578063972656a314610853576103db565b806376d8b117146107a757806381c0c263146107af57806382c63066146107b757806384e9bd7e146107bf576103db565b8063275f63e9116102fa5780634c87a0a51161028d5780636dd5b69d1161025c5780636dd5b69d1461071b5780636e553f651461073857806370a08231146107645780637598108c1461078a576103db565b80634c87a0a51461068b5780634d3ced19146106b957806352665f47146106e757806365fe945114610713576103db565b806338d07436116102c957806338d074361461061c5780633ccfd60b1461064157806343d7f86f146106495780634b82009314610651576103db565b8063275f63e9146105855780632e1a7d4d146105ab57806333134583146105c857806333fd6f74146105ee576103db565b806317e28089116103725780631d2747d4116103415780631d2747d41461052157806323a582921461054f5780632585581f14610557578063267716d21461055f576103db565b806317e28089146104e3578063180692d0146104eb57806318160ddd146104f35780631b9f546f146104fb576103db565b806313ecb1ca116103ae57806313ecb1ca1461046a57806313fa13681461049057806315fe96dc146104b657806316fa50b1146104db576103db565b806307546172146103e057806309400707146104045780630b54e7651461043c5780630c340a2414610462575b600080fd5b6103e8610bf3565b604080516001600160a01b039092168252519081900360200190f35b61042a6004803603602081101561041a57600080fd5b50356001600160a01b0316610c02565b60408051918252519081900360200190f35b61042a6004803603602081101561045257600080fd5b50356001600160a01b0316610c20565b6103e8610cdd565b61042a6004803603602081101561048057600080fd5b50356001600160a01b0316610cec565b61042a600480360360208110156104a657600080fd5b50356001600160a01b0316610cfe565b6104d9600480360360408110156104cc57600080fd5b5080359060200135610d42565b005b6103e8610d67565b61042a610d82565b61042a610d88565b61042a610d9a565b61042a6004803603602081101561051157600080fd5b50356001600160a01b0316610da0565b6104d96004803603604081101561053757600080fd5b506001600160a01b0381351690602001351515610dbe565b61042a610df4565b61042a610e06565b61042a6004803603602081101561057557600080fd5b50356001600160a01b0316610e18565b61042a6004803603602081101561059b57600080fd5b50356001600160a01b0316610e36565b6104d9600480360360208110156105c157600080fd5b5035610ea7565b61042a600480360360208110156105de57600080fd5b50356001600160a01b0316610eff565b61042a6004803603604081101561060457600080fd5b506001600160a01b0381358116916020013516611004565b6104d96004803603604081101561063257600080fd5b508035906020013515156110cb565b6104d9611156565b61042a611171565b6106776004803603602081101561066757600080fd5b50356001600160a01b0316611183565b604080519115158252519081900360200190f35b61042a600480360360408110156106a157600080fd5b506001600160a01b03813581169160200135166111e2565b61042a600480360360408110156106cf57600080fd5b506001600160a01b038135811691602001351661120b565b61042a600480360360408110156106fd57600080fd5b50803590602001356001600160a01b0316611234565b61042a611250565b61042a6004803603602081101561073157600080fd5b5035611262565b6104d96004803603604081101561074e57600080fd5b50803590602001356001600160a01b0316611274565b61042a6004803603602081101561077a57600080fd5b50356001600160a01b03166113b9565b61042a600480360360208110156107a057600080fd5b50356113cb565b6103e86113eb565b6104d96113fa565b6103e861145b565b6104d9600480360360208110156107d557600080fd5b50356001600160a01b031661146a565b6104d9600480360360408110156107fb57600080fd5b50803590602001351515611693565b61042a6004803603604081101561082057600080fd5b5080359060200135611711565b6104d96004803603602081101561084357600080fd5b50356001600160a01b0316611724565b61042a6004803603604081101561086957600080fd5b506001600160a01b038135811691602001351661172f565b61042a6004803603602081101561089757600080fd5b50356001600160a01b0316611758565b61042a600480360360208110156108bd57600080fd5b50356001600160a01b0316611776565b61042a6117ba565b6104d9600480360360608110156108eb57600080fd5b508035906001600160a01b0360208201351690604001356117f1565b6104d96004803603602081101561091d57600080fd5b50356001600160a01b0316611822565b6104d96004803603602081101561094357600080fd5b5035611842565b61042a61184c565b6103e8611852565b6104d96004803603606081101561097057600080fd5b506001600160a01b03813581169160208101358216916040909101351661186d565b6104d9600480360360208110156109a857600080fd5b50356001600160a01b0316611a2f565b61042a600480360360208110156109ce57600080fd5b50356001600160a01b0316611b20565b61042a600480360360208110156109f457600080fd5b50356001600160a01b0316611cf9565b61042a611f7d565b6104d960048036036060811015610a2257600080fd5b5080359060208101359060400135611f8f565b61042a60048036036020811015610a4b57600080fd5b50356001600160a01b0316611fb2565b6103e8611fd0565b61067760048036036040811015610a7957600080fd5b506001600160a01b0381358116916020013516611fdf565b6104d9611fff565b610aa1612008565b60408051600f9290920b8252519081900360200190f35b61042a612011565b6103e860048036036020811015610ad657600080fd5b5035612023565b6103e8612056565b6104d9600480360360a0811015610afb57600080fd5b6001600160a01b03823581169260208101358216926040820135831692606083013516919081019060a081016080820135640100000000811115610b3e57600080fd5b820183602082011115610b5057600080fd5b80359060200191846020830284011164010000000083111715610b7257600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612065945050505050565b61042a60048036036020811015610bc657600080fd5b50356001600160a01b0316612418565b61042a60048036036020811015610bec57600080fd5b503561245c565b6035546001600160a01b031681565b6c02863c1f5cdae42f95400000436020526000908152604090205481565b6001600160a01b0380821660009081526c02863c1f5cdae42f9540000049602090815260408083206c02863c1f5cdae42f95400000455482516316fa50b160e01b8152925194959194869491909216926316fa50b19260048083019392829003018186803b158015610c9157600080fd5b505afa158015610ca5573d6000803e3d6000fd5b505050506040513d6020811015610cbb57600080fd5b50516001600160a01b0316815260208101919091526040016000205492915050565b6033546001600160a01b031681565b603e6020526000908152604090205481565b6001600160a01b0390811660009081526c02863c1f5cdae42f9540000048602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6033546001600160a01b03163314610d5957600080fd5b610d638282612481565b5050565b6c02863c1f5cdae42f9540000046546001600160a01b031681565b603f5481565b6c02863c1f5cdae42f95400000445481565b603b5481565b6c02863c1f5cdae42f954000004d6020526000908152604090205481565b6001600160a01b03919091166000908152603d602090815260408083203384529091529020805460ff1916911515919091179055565b6c02863c1f5cdae42f95400000505481565b6c02863c1f5cdae42f954000004b5481565b6c02863c1f5cdae42f95400000476020526000908152604090205481565b6001600160a01b0380821660009081526c02863c1f5cdae42f954000004a602090815260408083206c02863c1f5cdae42f95400000455482516316fa50b160e01b8152925194959194869491909216926316fa50b19260048083019392829003018186803b158015610c9157600080fd5b6c636c61696d5f7265776172647360981b60005260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff854610efc90829015610ef4576001610ef7565b60005b6110cb565b50565b603554604080516308b752bb60e41b81526001600160a01b0384811660048301523060248301529151600093610fad931691638b752bb0916044808301926020929190829003018186803b158015610f5657600080fd5b505afa158015610f6a573d6000803e3d6000fd5b505050506040513d6020811015610f8057600080fd5b50516001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902054906124a8565b9050610ffe610ff783610fbe6124ea565b6c02863c1f5cdae42f954000004e546001600160a01b03871660009081526c02863c1f5cdae42f954000004d602052604090205461269a565b8290612734565b92915050565b6001600160a01b0380821660008181526c02863c1f5cdae42f9540000047602090815260408083205494871683526c02863c1f5cdae42f9540000048825280832093835292905290812054909161105e918591849161269a565b6001600160a01b0380851660008181526c02863c1f5cdae42f954000004a60209081526040808320948816808452948252808320549383526c02863c1f5cdae42f9540000049825280832094835293905291909120549192506110c491610ff7916124a8565b9392505050565b6110d5338261278e565b603b546110e290836124a8565b603b55336000908152603a60205260409020546110ff90836124a8565b336000818152603a602052604090209190915561111c908361292a565b60408051838152905133917f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364919081900360200190a25050565b336000908152603a602052604090205461116f90610ea7565b565b6c02863c1f5cdae42f954000004f5481565b6c636c61696d5f7265776172647360981b600090815260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff8546111da908390156111d25760016111d5565b60005b61278e565b506001919050565b6c02863c1f5cdae42f954000004860209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f954000004a60209081526000928352604080842090915290825290205481565b6001600160a01b03161860009081526034602052604090205490565b6c02863c1f5cdae42f954000004e5481565b60009081526034602052604090205490565b6001600160a01b0381163314806112ae5750336000908152603d602090815260408083206001600160a01b038516845290915290205460ff165b6112ee576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b6c636c61696d5f7265776172647360981b60005260346020527f684da2165171dc71a63fa7e63bc201bb3b7b8a39bd56bf2e6eba52a048e47ff85461133b908290156111d25760016111d5565b61134581836129a5565b336000908152603a602052604090205461135f9083612734565b336000908152603a6020526040902055603b5461137c9083612734565b603b5560408051838152905133917fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c919081900360200190a25050565b603a6020526000908152604090205481565b6041816c01431e0fae6d7217caa000000081106113e457fe5b0154905081565b6036546001600160a01b031681565b6033546001600160a01b0316331461141157600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b6037546001600160a01b031681565b6c02863c1f5cdae42f954000004b5415806114855750603b54155b1561148f57610efc565b61149a816001612a45565b60005b6c02863c1f5cdae42f954000005154811015610d63576001600160a01b03821660009081526c02863c1f5cdae42f954000004a602052604081206c02863c1f5cdae42f9540000051805461158292918491869081106114f857fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493881682526c02863c1f5cdae42f954000004990529081206c02863c1f5cdae42f954000005180549192918790811061155757fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902054906124a8565b9050801561168a576115c483826c02863c1f5cdae42f954000005185815481106115a857fe5b6000918252602090912001546001600160a01b03169190613195565b6001600160a01b03831660009081526c02863c1f5cdae42f9540000049602052604081206c02863c1f5cdae42f954000005180549192918590811061160557fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493871682526c02863c1f5cdae42f954000004a90529081206c02863c1f5cdae42f954000005180549192918690811061166457fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b5060010161149d565b6033546001600160a01b031633146116aa57600080fd5b6c02863c1f5cdae42f954000004b82905580156116d8574282016c02863c1f5cdae42f954000004c556116ea565b60006c02863c1f5cdae42f954000004c555b6c02863c1f5cdae42f954000005054610d6357426c02863c1f5cdae42f9540000050555050565b1860009081526034602052604090205490565b610efc81600161278e565b6c02863c1f5cdae42f954000004960209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f95400000426020526000908152604090205481565b6001600160a01b0390811660009081526c02863c1f5cdae42f9540000049602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c02863c1f5cdae42f9540000046546001600160a01b031660009081526c02863c1f5cdae42f954000004760205260409020545b90565b6033546001600160a01b0316331461180857600080fd5b61181d6001600160a01b038316841882612481565b505050565b6033546001600160a01b0316331461183957600080fd5b610efc816132ff565b610efc8133611274565b603c5481565b6c02863c1f5cdae42f9540000045546001600160a01b031681565b600054610100900460ff1680611886575061188661336e565b80611894575060005460ff16155b6118cf5760405162461bcd60e51b815260040180806020018281038252602e815260200180613a8b602e913960400191505060405180910390fd5b600054610100900460ff161580156118fa576000805460ff1961ff0019909116610100171660011790555b61190384611a2f565b603580546001600160a01b0319166001600160a01b03851690811790915560408051637e062a3560e11b8152905163fc0c546a91600480820192602092909190829003018186803b15801561195757600080fd5b505afa15801561196b573d6000803e3d6000fd5b505050506040513d602081101561198157600080fd5b5051603680546001600160a01b03199081166001600160a01b0393841617909155603780549091168483161790819055604080516318160ddd60e01b8152905191909216916318160ddd916004808301926020929190829003018186803b1580156119eb57600080fd5b505afa1580156119ff573d6000803e3d6000fd5b505050506040513d6020811015611a1557600080fd5b50508015611a29576000805461ff00191690555b50505050565b600054610100900460ff1680611a485750611a4861336e565b80611a56575060005460ff16155b611a915760405162461bcd60e51b815260040180806020018281038252602e815260200180613a8b602e913960400191505060405180910390fd5b600054610100900460ff16158015611abc576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a38015610d63576000805461ff00191690555050565b6c02863c1f5cdae42f9540000045546040805163d2797b5960e01b8152306004820152905160009283926001600160a01b039091169163d2797b5991602480820192602092909190829003018186803b158015611b7c57600080fd5b505afa158015611b90573d6000803e3d6000fd5b505050506040513d6020811015611ba657600080fd5b50516c02863c1f5cdae42f954000004554604080516316fa50b160e01b815290519293506000926001600160a01b03909216916316fa50b191600480820192602092909190829003018186803b158015611bff57600080fd5b505afa158015611c13573d6000803e3d6000fd5b505050506040513d6020811015611c2957600080fd5b50516001600160a01b0380821660008181526c02863c1f5cdae42f95400000476020908152604080832054948a1683526c02863c1f5cdae42f954000004882528083209383529290522054919250611c84918691859161269a565b6001600160a01b0380861660008181526c02863c1f5cdae42f954000004a60209081526040808320948716808452948252808320549383526c02863c1f5cdae42f954000004982528083209483529390529190912054919450611cf191611cea916124a8565b8490612734565b949350505050565b600080611e996c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663075461726040518163ffffffff1660e01b815260040160206040518083038186803b158015611d5957600080fd5b505afa158015611d6d573d6000803e3d6000fd5b505050506040513d6020811015611d8357600080fd5b50516c02863c1f5cdae42f954000004554604080516308b752bb60e41b81523060048201526001600160a01b03928316602482015290519190921691638b752bb0916044808301926020929190829003018186803b158015611de457600080fd5b505afa158015611df8573d6000803e3d6000fd5b505050506040513d6020811015611e0e57600080fd5b50516c02863c1f5cdae42f95400000455460408051630940070760e01b815230600482015290516001600160a01b0390921691630940070791602480820192602092909190829003018186803b158015611e6757600080fd5b505afa158015611e7b573d6000803e3d6000fd5b505050506040513d6020811015611e9157600080fd5b5051906124a8565b6c02863c1f5cdae42f9540000046546001600160a01b0390811660008181526c02863c1f5cdae42f9540000047602090815260408083205494891683526c02863c1f5cdae42f954000004882528083209383529290522054919250611f01918591849161269a565b6001600160a01b0380851660008181526c02863c1f5cdae42f954000004a602090815260408083206c02863c1f5cdae42f954000004654909516808452948252808320549383526c02863c1f5cdae42f9540000049825280832094835293905291909120549193506110c491611f76916124a8565b8390612734565b6c02863c1f5cdae42f95400000505490565b6033546001600160a01b03163314611fa657600080fd5b61181d83831882612481565b6c02863c1f5cdae42f95400000416020526000908152604090205481565b6039546001600160a01b031681565b603d60209081526000928352604080842090915290825290205460ff1681565b61116f3361146a565b604054600f0b81565b6c02863c1f5cdae42f954000004c5481565b6c02863c1f5cdae42f9540000051818154811061203c57fe5b6000918252602090912001546001600160a01b0316905081565b6038546001600160a01b031681565b600054610100900460ff168061207e575061207e61336e565b8061208c575060005460ff16155b6120c75760405162461bcd60e51b815260040180806020018281038252602e815260200180613a8b602e913960400191505060405180910390fd5b600054610100900460ff161580156120f2576000805460ff1961ff0019909116610100171660011790555b6120fd86868661186d565b6c02863c1f5cdae42f954000004580546001600160a01b0319166001600160a01b038516908117909155604080516376d8b11760e01b815290516376d8b11791600480820192602092909190829003018186803b15801561215d57600080fd5b505afa158015612171573d6000803e3d6000fd5b505050506040513d602081101561218757600080fd5b50516c02863c1f5cdae42f954000004680546001600160a01b0319166001600160a01b0390921691909117905581516121d3906c02863c1f5cdae42f95400000519060208501906139e5565b506c02863c1f5cdae42f9540000046546c02863c1f5cdae42f9540000051805460018101825560009182527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b03938416179055604080516316fa50b160e01b8152905191928616916316fa50b191600480820192602092909190829003018186803b15801561227557600080fd5b505afa158015612289573d6000803e3d6000fd5b505050506040513d602081101561229f57600080fd5b505190506001600160a01b0381161561230a576c02863c1f5cdae42f954000005180546001810182556000919091527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b0383161790555b836001600160a01b031663d31f3f6d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561234357600080fd5b505afa158015612357573d6000803e3d6000fd5b505050506040513d602081101561236d57600080fd5b50600090505b83518110156123fc5783818151811061238857fe5b60200260200101516001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156123c857600080fd5b505afa1580156123dc573d6000803e3d6000fd5b505050506040513d60208110156123f257600080fd5b5050600101612373565b50508015612410576000805461ff00191690555b505050505050565b6001600160a01b0390811660009081526c02863c1f5cdae42f954000004a602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c01431e0fae6d7217caa0000041816c01431e0fae6d7217caa000000081106113e457fe5b6000828152603460205260409020548114610d635760009182526034602052604090912055565b60006110c483836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613374565b60006c02863c1f5cdae42f954000004b54600014806125095750603b54155b15612516575060006117ee565b6c02863c1f5cdae42f954000004f546035546040805163c33342e960e01b8152306004820152905161257293926001600160a01b03169163c33342e9916024808301926020929190829003018186803b158015611e6757600080fd5b90506c02863c1f5cdae42f954000004c5460001415612605576c02863c1f5cdae42f954000004b546c02863c1f5cdae42f9540000050546125b49042906124a8565b1015612600576125fd6c02863c1f5cdae42f954000004b546125f76125f06c02863c1f5cdae42f954000005054426124a890919063ffffffff16565b849061340b565b90613464565b90505b6117ee565b6c02863c1f5cdae42f954000004c54421015612671576125fd61264d6c02863c1f5cdae42f9540000050546c02863c1f5cdae42f954000004c546124a890919063ffffffff16565b6125f76125f06c02863c1f5cdae42f954000005054426124a890919063ffffffff16565b6c02863c1f5cdae42f954000004c546c02863c1f5cdae42f954000005054106117ee5750600090565b60006c02863c1f5cdae42f954000004b54600014806126b95750603b54155b156126c657506000611cf1565b6126d083836124a8565b90506126f6610ff7603b546125f7670de0b6b3a76400008861340b90919063ffffffff16565b6001600160a01b0386166000908152603a602052604090205490915061272b90670de0b6b3a7640000906125f790849061340b565b95945050505050565b6000828201838110156110c4576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6c02863c1f5cdae42f954000004b5415806127a95750603b54155b156127b357610d63565b60006127bd6124ea565b9050600061280c84836c02863c1f5cdae42f954000004e546c02863c1f5cdae42f954000004d6000896001600160a01b03166001600160a01b031681526020019081526020016000205461269a565b9050808214612850576128408161283a846c02863c1f5cdae42f954000004f5461273490919063ffffffff16565b906124a8565b6c02863c1f5cdae42f954000004f555b811561289857603b5461288890612873906125f785670de0b6b3a764000061340b565b6c02863c1f5cdae42f954000004e5490612734565b6c02863c1f5cdae42f954000004e555b6c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d602052604090205414612906576c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020555b426c02863c1f5cdae42f95400000505561292084826134a6565b611a298484612a45565b6c02863c1f5cdae42f95400000455460408051632e1a7d4d60e01b81526004810184905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b15801561298357600080fd5b505af1158015612997573d6000803e3d6000fd5b50505050610d638282613699565b6129af82826136b0565b6c02863c1f5cdae42f9540000045546037546129d8916001600160a01b039182169116836136c8565b6c02863c1f5cdae42f9540000045546040805163b6b55f2560e01b81526004810184905290516001600160a01b039092169163b6b55f259160248082019260009290919082900301818387803b158015612a3157600080fd5b505af1158015612410573d6000803e3d6000fd5b6c02863c1f5cdae42f954000004b541580612a605750603b54155b15612a6a57610d63565b6c02863c1f5cdae42f95400000515460609067ffffffffffffffff81118015612a9257600080fd5b50604051908082528060200260200182016040528015612abc578160200160208202803683370190505b5090508115612d9f5760005b8151811015612b86576c02863c1f5cdae42f95400000518181548110612aea57fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b158015612b3957600080fd5b505afa158015612b4d573d6000803e3d6000fd5b505050506040513d6020811015612b6357600080fd5b50518251839083908110612b7357fe5b6020908102919091010152600101612ac8565b506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663075461726040518163ffffffff1660e01b815260040160206040518083038186803b158015612be157600080fd5b505afa158015612bf5573d6000803e3d6000fd5b505050506040513d6020811015612c0b57600080fd5b50516c02863c1f5cdae42f954000004554604080516335313c2160e11b81526001600160a01b03928316600482015290519190921691636a62784291602480830192600092919082900301818387803b158015612c6757600080fd5b505af1158015612c7b573d6000803e3d6000fd5b505050506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663e6f1daf26040518163ffffffff1660e01b8152600401600060405180830381600087803b158015612cdb57600080fd5b505af1158015612cef573d6000803e3d6000fd5b5050505060005b8151811015612d9d57612d7e828281518110612d0e57fe5b60200260200101516c02863c1f5cdae42f95400000518381548110612d2f57fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b158015611e6757600080fd5b828281518110612d8a57fe5b6020908102919091010152600101612cf6565b505b60005b8151811015611a29576000612e7785848481518110612dbd57fe5b60200260200101516c02863c1f5cdae42f954000004760006c02863c1f5cdae42f95400000518781548110612dee57fe5b60009182526020808320909101546001600160a01b039081168452838201949094526040928301822054938c1682526c02863c1f5cdae42f954000004890529081206c02863c1f5cdae42f9540000051805491929189908110612e4d57fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205461269a565b90508015612f6157612efa816c02863c1f5cdae42f95400000496000886001600160a01b03166001600160a01b0316815260200190815260200160002060006c02863c1f5cdae42f95400000518681548110612ecf57fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205490612734565b6001600160a01b03861660009081526c02863c1f5cdae42f9540000049602052604081206c02863c1f5cdae42f9540000051805491929186908110612f3b57fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b6000838381518110612f6f57fe5b6020026020010151111561302c57612fdd612fb4603b546125f7670de0b6b3a7640000878781518110612f9e57fe5b602002602001015161340b90919063ffffffff16565b6c02863c1f5cdae42f954000004760006c02863c1f5cdae42f95400000518681548110612ecf57fe5b6c02863c1f5cdae42f954000004760006c02863c1f5cdae42f9540000051858154811061300657fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b6c02863c1f5cdae42f954000004760006c02863c1f5cdae42f9540000051848154811061305557fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493891682526c02863c1f5cdae42f954000004890529081206c02863c1f5cdae42f95400000518054919291869081106130b457fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020541461318c576c02863c1f5cdae42f954000004760006c02863c1f5cdae42f9540000051848154811061310757fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493891682526c02863c1f5cdae42f954000004890529081206c02863c1f5cdae42f954000005180549192918690811061316657fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b50600101612da2565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b602083106132125780518252601f1990920191602091820191016131f3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613274576040519150601f19603f3d011682016040523d82523d6000602084013e613279565b606091505b50915091508180156132a75750805115806132a757508080602001905160208110156132a457600080fd5b50515b6132f8576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b5050505050565b6001600160a01b03811661331257600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b303b1590565b600081848411156134035760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156133c85781810151838201526020016133b0565b50505050905090810190601f1680156133f55780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b60008261341a57506000610ffe565b8282028284828161342757fe5b04146110c45760405162461bcd60e51b8152600401808060200182810382526021815260200180613a6a6021913960400191505060405180910390fd5b60006110c483836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061382b565b8015610d63576001600160a01b03821660009081526c02863c1f5cdae42f954000004360205260409020546134db9082612734565b6001600160a01b0392831660009081526c02863c1f5cdae42f95400000436020908152604082209290925560349091527fe9b68ca2b566af5bdfbb3361c12fcbb5dbf956c250bbd74cc175cc06ec62c7915467646576526174696f60c01b9091527fb8fbd2e70438ec482a0e7fc9b87580647182c1694aea1065027a1d634e92d6b954909283161580159061356f57508015155b156135de576135b861358d670de0b6b3a76400006125f7858561340b565b6001600160a01b03851660009081526c02863c1f5cdae42f9540000043602052604090205490612734565b6001600160a01b03841660009081526c02863c1f5cdae42f954000004360205260409020555b5060346020527f82e0b58992d24d827851dcbd63485b5933f9d3ae4c2ca50477d1437e73f6d342546765636f526174696f60c01b6000527ffc6561c6b7742261fbeab673eba1bedd2f5b1d7221f757ea8c9a87d664cfbed2549092506001600160a01b0383161580159061365157508015155b1561181d5761366f61358d670de0b6b3a76400006125f7858561340b565b6001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902055505050565b603754610d63906001600160a01b03168383613195565b603754610d63906001600160a01b0316833084613890565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663095ea7b360e01b178152925182516000946060949389169392918291908083835b602083106137455780518252601f199092019160209182019101613726565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146137a7576040519150601f19603f3d011682016040523d82523d6000602084013e6137ac565b606091505b50915091508180156137da5750805115806137da57508080602001905160208110156137d757600080fd5b50515b6132f8576040805162461bcd60e51b815260206004820152601e60248201527f5472616e7366657248656c7065723a20415050524f56455f4641494c45440000604482015290519081900360640190fd5b6000818361387a5760405162461bcd60e51b81526020600482018181528351602484015283519092839260449091019190850190808383600083156133c85781810151838201526020016133b0565b50600083858161388657fe5b0495945050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17815292518251600094606094938a169392918291908083835b602083106139155780518252601f1990920191602091820191016138f6565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613977576040519150601f19603f3d011682016040523d82523d6000602084013e61397c565b606091505b50915091508180156139aa5750805115806139aa57508080602001905160208110156139a757600080fd5b50515b6124105760405162461bcd60e51b8152600401808060200182810382526024815260200180613ab96024913960400191505060405180910390fd5b828054828255906000526020600020908101928215613a3a579160200282015b82811115613a3a57825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190613a05565b50613a46929150613a4a565b5090565b5b80821115613a465780546001600160a01b0319168155600101613a4b56fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c4544a2646970667358221220fa24d5cd97da211463fbb240d11d1753a4c976464d9aea9b05e085d4f576875264736f6c634300060c0033
[ 5, 4, 9, 7 ]
0x41624F34142C181BD3BeDd95867b62Ac94b4C265
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { /** * @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 Constants { address constant CDP_MANAGER = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address constant PROXY_ACTIONS = 0x82ecD135Dce65Fbc6DbdD0e4237E0AF93FFD5038; address constant MCD_JOIN_ETH_A = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address constant MCD_JOIN_USDC_A = 0xA191e578a6736167326d05c119CE0c90849E84B7; address constant MCD_JOIN_DAI = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address constant MCD_JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address constant MCD_END = 0xaB14d3CE3F733CACB76eC2AbE7d2fcb00c99F3d5; address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address constant UNISWAPV2_ROUTER2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; bytes32 constant USDC_A_ILK = bytes32("USDC-A"); bytes32 constant ETH_A_ILK = bytes32("ETH-A"); } contract Migrations { address public owner; uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } } contract ShortDAIActions { using SafeMath for uint256; function _openUSDCACdp() internal returns (uint256) { return IDssCdpManager(Constants.CDP_MANAGER).open( bytes32("USDC-A"), address(this) ); } // Entry point for proxy contracts function flashloanAndOpen( address _osd, address _solo, address _curvePool, uint256 _cdpId, // Set 0 for new vault uint256 _initialMarginUSDC, // Initial USDC margin uint256 _mintAmountDAI, // Amount of DAI to mint uint256 _flashloanAmountWETH, // Amount of WETH to flashloan address _vaultStats, uint256 _daiUsdcRatio6 ) external payable { require(msg.value == 2, "!fee"); // Tries and get USDC from msg.sender to proxy require( IERC20(Constants.USDC).transferFrom( msg.sender, address(this), _initialMarginUSDC ), "initial-margin-transferFrom-failed" ); uint256 cdpId = _cdpId; // Opens a new USDC vault for the user if unspecified if (cdpId == 0) { cdpId = _openUSDCACdp(); } // Allows LSD contract to manage vault on behalf of user IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(cdpId, _osd, 1); // Approve OpenShortDAI Contract to use USDC funds require( IERC20(Constants.USDC).approve(_osd, _initialMarginUSDC), "initial-margin-approve-failed" ); // Flashloan and shorts DAI OpenShortDAI(_osd).flashloanAndOpen{value: msg.value}( msg.sender, _solo, _curvePool, cdpId, _initialMarginUSDC, _mintAmountDAI, _flashloanAmountWETH ); // Forbids LSD contract to manage vault on behalf of user IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(cdpId, _osd, 0); // Save stats VaultStats(_vaultStats).setDaiUsdcRatio6(cdpId, _daiUsdcRatio6); } function flashloanAndClose( address _csd, address _solo, address _curvePool, uint256 _cdpId, uint256 _ethUsdRatio18 ) external payable { require(msg.value == 2, "!fee"); IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(_cdpId, _csd, 1); CloseShortDAI(_csd).flashloanAndClose{value: msg.value}( msg.sender, _solo, _curvePool, _cdpId, _ethUsdRatio18 ); IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(_cdpId, _csd, 0); IDssCdpManager(Constants.CDP_MANAGER).give(_cdpId, address(1)); } function cdpAllow( uint256 cdp, address usr, uint256 ok ) public { IDssCdpManager(Constants.CDP_MANAGER).cdpAllow(cdp, usr, ok); } } contract VaultStats { uint256 constant RAY = 10**27; using SafeMath for uint256; // CDP ID => DAI/USDC Ratio in 6 decimals // i.e. What was DAI/USDC ratio when CDP was opened mapping(uint256 => uint256) public daiUsdcRatio6; //** View functions for stats ** // function _getCdpSuppliedAndBorrowed( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint256, uint256) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (uint256 supplied, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = art.mul(rate).sub(dai); uint256 wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei uint256 borrowed = wad.mul(RAY) < rad ? wad + 1 : wad; // Note that supplied is in 18 decimals, so you'll need to convert it back // i.e. supplied = supplied / 10 ** (18 - decimals) return (supplied, borrowed); } // Get DAI borrow / supply stats function getCdpStats(uint256 cdp) public view returns ( uint256, uint256, uint256 ) { address vat = IDssCdpManager(Constants.CDP_MANAGER).vat(); address urn = IDssCdpManager(Constants.CDP_MANAGER).urns(cdp); bytes32 ilk = IDssCdpManager(Constants.CDP_MANAGER).ilks(cdp); address usr = IDssCdpManager(Constants.CDP_MANAGER).owns(cdp); (uint256 supplied, uint256 borrowed) = _getCdpSuppliedAndBorrowed( vat, usr, urn, ilk ); uint256 ratio = daiUsdcRatio6[cdp]; // Note that supplied and borrowed are in 18 decimals // while DAI USDC ratio is in 6 decimals return (supplied, borrowed, ratio); } function setDaiUsdcRatio6(uint256 _cdp, uint256 _daiUsdcRatio6) public { IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER); address owner = manager.owns(_cdp); require( owner == msg.sender || manager.cdpCan(owner, _cdp, msg.sender) == 1, "cdp-not-allowed" ); daiUsdcRatio6[_cdp] = _daiUsdcRatio6; } } interface ICurveFiCurve { function get_virtual_price() external view returns (uint256 out); function add_liquidity(uint256[2] calldata amounts, uint256 deadline) external; function get_dy( int128 i, int128 j, uint256 dx ) external view returns (uint256 out); function get_dy_underlying( int128 i, int128 j, uint256 dx ) external view returns (uint256 out); function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy ) external; function exchange_underlying( int128 i, int128 j, uint256 dx, uint256 min_dy, uint256 deadline ) external; function remove_liquidity( uint256 _amount, uint256 deadline, uint256[2] calldata min_amounts ) external; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 deadline ) external; function commit_new_parameters( int128 amplification, int128 new_fee, int128 new_admin_fee ) external; function apply_new_parameters() external; function revert_new_parameters() external; function commit_transfer_ownership(address _owner) external; function apply_transfer_ownership() external; function revert_transfer_ownership() external; function withdraw_admin_fees() external; function coins(int128 arg0) external returns (address out); function underlying_coins(int128 arg0) external returns (address out); function balances(int128 arg0) external returns (uint256 out); function A() external returns (int128 out); function fee() external returns (int128 out); function admin_fee() external returns (int128 out); function owner() external returns (address out); function admin_actions_deadline() external returns (uint256 out); function transfer_ownership_deadline() external returns (uint256 out); function future_A() external returns (int128 out); function future_fee() external returns (int128 out); function future_admin_fee() external returns (int128 out); function future_owner() external returns (address out); } contract DydxFlashloanBase { using SafeMath for uint256; // -- Internal Helper functions -- // function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) { ISoloMargin solo = ISoloMargin(_solo); uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found for provided token"); } function _getRepaymentAmount() internal pure returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return 2; } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } struct Storage { mapping(uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } struct CallArgs { Account.Info account; address callee; bytes data; } } library Decimal { struct D256 { uint256 value; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct TotalPar { uint128 borrow; uint128 supply; } struct Par { bool sign; // true if positive uint128 value; } struct Wei { bool sign; // true if positive uint256 value; } } interface ISoloMargin { function getMarketTokenAddress(uint256 marketId) external view returns (address); function getNumMarkets() external view returns (uint256); function operate( Account.Info[] calldata accounts, Actions.ActionArgs[] calldata actions ) external; } interface ICallee { // ============ external Functions ============ /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info calldata accountInfo, bytes calldata data ) external; } interface GemLike { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; } interface GemJoinLike { function dec() external returns (uint256); function gem() external returns (address); function join(address, uint256) external payable; function exit(address, uint256) external; } interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob( bytes32, address, address, address, int256, int256 ) external; function hope(address) external; function move( address, address, uint256 ) external; } interface JugLike { function drip(bytes32) external returns (uint256); function ilks(bytes32) external view returns (uint256, uint256); } interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } contract DssActionsBase { uint256 constant RAY = 10**27; using SafeMath for uint256; function _convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec())); } function _toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function _toRad(uint256 wad) internal pure returns (uint256 rad) { rad = wad.mul(10**27); } function _gemJoin_join( address apt, address urn, uint256 wad, bool transferFrom ) internal { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Tokens already in address(this) // GemLike(GemJoinLike(apt).gem()).transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemLike(GemJoinLike(apt).gem()).approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function _daiJoin_join( address apt, address urn, uint256 wad ) internal { // Contract already has tokens // Gets DAI from the user's wallet // DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint256 wad ) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < wad.mul(RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = _toInt(wad.mul(RAY).sub(dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint256 dai, address urn, bytes32 ilk ) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = _toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -_toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = art.mul(rate).sub(dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = wad.mul(RAY) < rad ? wad + 1 : wad; } function _getSuppliedAndBorrow(address gemJoin, uint256 cdp) internal returns (uint256, uint256) { IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER); address vat = manager.vat(); bytes32 ilk = manager.ilks(cdp); // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (uint256 supplied, uint256 art) = VatLike(vat).urns( ilk, manager.urns(cdp) ); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(manager.owns(cdp)); uint256 rad = art.mul(rate).sub(dai); uint256 wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei uint256 borrowed = wad.mul(RAY) < rad ? wad + 1 : wad; // Convert back to native units supplied = supplied.div(10**(18 - GemJoinLike(gemJoin).dec())); return (supplied, borrowed); } function _lockGemAndDraw( address gemJoin, uint256 cdp, uint256 wadC, uint256 wadD ) internal { IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER); address urn = manager.urns(cdp); address vat = manager.vat(); bytes32 ilk = manager.ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat _gemJoin_join(gemJoin, urn, wadC, true); // Locks GEM amount into the CDP and generates debt manager.frob( cdp, _toInt(_convertTo18(gemJoin, wadC)), _getDrawDart(vat, Constants.MCD_JUG, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address manager.move(cdp, address(this), _toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if ( VatLike(vat).can(address(this), address(Constants.MCD_JOIN_DAI)) == 0 ) { VatLike(vat).hope(Constants.MCD_JOIN_DAI); } // Exits DAI to the user's wallet as a token DaiJoinLike(Constants.MCD_JOIN_DAI).exit(address(this), wadD); } function _wipeAllAndFreeGem( address gemJoin, uint256 cdp, uint256 amtC ) internal { IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER); address vat = manager.vat(); address urn = manager.urns(cdp); bytes32 ilk = manager.ilks(cdp); (, uint256 art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat _daiJoin_join( Constants.MCD_JOIN_DAI, urn, _getWipeAllWad(vat, urn, urn, ilk) ); uint256 wadC = _convertTo18(gemJoin, amtC); // Paybacks debt to the CDP and unlocks token amount from it manager.frob(cdp, -_toInt(wadC), -int256(art)); // Moves the amount from the CDP urn to proxy's address manager.flux(cdp, address(this), wadC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(address(this), amtC); } function _openLockGemAndDraw( address gemJoin, bytes32 ilk, uint256 amtC, uint256 wadD ) internal returns (uint256 cdp) { cdp = IDssCdpManager(Constants.CDP_MANAGER).open(ilk, address(this)); _lockGemAndDraw(gemJoin, cdp, amtC, wadD); } } interface IDSProxy { function authority() external view returns (address); function cache() external view returns (address); function execute(address _target, bytes calldata _data) external payable returns (bytes memory response); function execute(bytes calldata _code, bytes calldata _data) external payable returns (address target, bytes memory response); function owner() external view returns (address); function setAuthority(address authority_) external; function setCache(address _cacheAddr) external returns (bool); function setOwner(address owner_) external; } interface IDssCdpManager { function cdpAllow( uint256 cdp, address usr, uint256 ok ) external; function cdpCan( address, uint256, address ) external view returns (uint256); function cdpi() external view returns (uint256); function count(address) external view returns (uint256); function enter(address src, uint256 cdp) external; function first(address) external view returns (uint256); function flux( bytes32 ilk, uint256 cdp, address dst, uint256 wad ) external; function flux( uint256 cdp, address dst, uint256 wad ) external; function frob( uint256 cdp, int256 dink, int256 dart ) external; function give(uint256 cdp, address dst) external; function ilks(uint256) external view returns (bytes32); function last(address) external view returns (uint256); function list(uint256) external view returns (uint256 prev, uint256 next); function move( uint256 cdp, address dst, uint256 rad ) external; function open(bytes32 ilk, address usr) external returns (uint256); function owns(uint256) external view returns (address); function quit(uint256 cdp, address dst) external; function shift(uint256 cdpSrc, uint256 cdpDst) external; function urnAllow(address usr, uint256 ok) external; function urnCan(address, address) external view returns (uint256); function urns(uint256) external view returns (address); function vat() external view returns (address); } interface IDssProxyActions { function cdpAllow( address manager, uint256 cdp, address usr, uint256 ok ) external; function daiJoin_join( address apt, address urn, uint256 wad ) external; function draw( address manager, address jug, address daiJoin, uint256 cdp, uint256 wad ) external; function enter( address manager, address src, uint256 cdp ) external; function ethJoin_join(address apt, address urn) external payable; function exitETH( address manager, address ethJoin, uint256 cdp, uint256 wad ) external; function exitGem( address manager, address gemJoin, uint256 cdp, uint256 amt ) external; function flux( address manager, uint256 cdp, address dst, uint256 wad ) external; function freeETH( address manager, address ethJoin, uint256 cdp, uint256 wad ) external; function freeGem( address manager, address gemJoin, uint256 cdp, uint256 amt ) external; function frob( address manager, uint256 cdp, int256 dink, int256 dart ) external; function gemJoin_join( address apt, address urn, uint256 amt, bool transferFrom ) external; function give( address manager, uint256 cdp, address usr ) external; function giveToProxy( address proxyRegistry, address manager, uint256 cdp, address dst ) external; function hope(address obj, address usr) external; function lockETH( address manager, address ethJoin, uint256 cdp ) external payable; function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) external payable; function lockGem( address manager, address gemJoin, uint256 cdp, uint256 amt, bool transferFrom ) external; function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 amtC, uint256 wadD, bool transferFrom ) external; function makeGemBag(address gemJoin) external returns (address bag); function move( address manager, uint256 cdp, address dst, uint256 rad ) external; function nope(address obj, address usr) external; function open( address manager, bytes32 ilk, address usr ) external returns (uint256 cdp); function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD ) external payable returns (uint256 cdp); function openLockGNTAndDraw( address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint256 amtC, uint256 wadD ) external returns (address bag, uint256 cdp); function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 amtC, uint256 wadD, bool transferFrom ) external returns (uint256 cdp); function quit( address manager, uint256 cdp, address dst ) external; function safeLockETH( address manager, address ethJoin, uint256 cdp, address owner ) external payable; function safeLockGem( address manager, address gemJoin, uint256 cdp, uint256 amt, bool transferFrom, address owner ) external; function safeWipe( address manager, address daiJoin, uint256 cdp, uint256 wad, address owner ) external; function safeWipeAll( address manager, address daiJoin, uint256 cdp, address owner ) external; function shift( address manager, uint256 cdpSrc, uint256 cdpOrg ) external; function transfer( address gem, address dst, uint256 amt ) external; function urnAllow( address manager, address usr, uint256 ok ) external; function wipe( address manager, address daiJoin, uint256 cdp, uint256 wad ) external; function wipeAll( address manager, address daiJoin, uint256 cdp ) external; function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint256 cdp, uint256 wadC ) external; function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint256 cdp, uint256 amtC ) external; function wipeAndFreeETH( address manager, address ethJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD ) external; function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint256 cdp, uint256 amtC, uint256 wadD ) external; } interface IGetCdps { function getCdpsAsc(address manager, address guy) external view returns ( uint256[] memory ids, address[] memory urns, bytes32[] memory ilks ); function getCdpsDesc(address manager, address guy) external view returns ( uint256[] memory ids, address[] memory urns, bytes32[] memory ilks ); } interface IProxyRegistry { function build() external returns (address proxy); function proxies(address) external view returns (address); function build(address owner) external returns (address proxy); } interface IOneSplit { function getExpectedReturn( address fromToken, address destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) external view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address destToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 flags ) external payable returns (uint256 returnAmount); } interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); 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 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); } interface UniswapPair { function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestamp ); } interface WETH { function deposit() external payable; function withdraw(uint256 wad) external; function approve(address guy, uint256 wad) external returns (bool); function transfer(address dst, uint256 wad) external returns (bool); } contract CloseShortDAI is ICallee, DydxFlashloanBase, DssActionsBase { struct CSDParams { uint256 cdpId; // CdpId to close address curvePool; // Which curve pool to use uint256 mintAmountDAI; // Amount of DAI to mint uint256 withdrawAmountUSDC; // Amount of USDC to withdraw from vault uint256 flashloanAmountWETH; // Amount of WETH flashloaned } function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { CSDParams memory csdp = abi.decode(data, (CSDParams)); // Step 1. Have Flashloaned WETH // Open WETH CDP in Maker, then Mint out some DAI uint256 wethCdp = _openLockGemAndDraw( Constants.MCD_JOIN_ETH_A, Constants.ETH_A_ILK, csdp.flashloanAmountWETH, csdp.mintAmountDAI ); // Step 2. // Use flashloaned DAI to repay entire vault and withdraw USDC _wipeAllAndFreeGem( Constants.MCD_JOIN_USDC_A, csdp.cdpId, csdp.withdrawAmountUSDC ); // Step 3. // Converts USDC to DAI on CurveFi (To repay loan) // DAI = 0 index, USDC = 1 index ICurveFiCurve curve = ICurveFiCurve(csdp.curvePool); // Calculate amount of USDC needed to exchange to repay flashloaned DAI // Allow max of 5% slippage (otherwise no profits lmao) uint256 usdcBal = IERC20(Constants.USDC).balanceOf(address(this)); require( IERC20(Constants.USDC).approve(address(curve), usdcBal), "erc20-approve-curvepool-failed" ); curve.exchange_underlying(int128(1), int128(0), usdcBal, 0); // Step 4. // Repay DAI loan back to WETH CDP and FREE WETH _wipeAllAndFreeGem( Constants.MCD_JOIN_ETH_A, wethCdp, csdp.flashloanAmountWETH ); } function flashloanAndClose( address _sender, address _solo, address _curvePool, uint256 _cdpId, uint256 _ethUsdRatio18 // 1 ETH = <X> DAI? ) external payable { require(msg.value == 2, "!fee"); ISoloMargin solo = ISoloMargin(_solo); uint256 marketId = _getMarketIdFromTokenAddress(_solo, Constants.WETH); // Supplied = How much we want to withdraw // Borrowed = How much we want to loan ( uint256 withdrawAmountUSDC, uint256 mintAmountDAI ) = _getSuppliedAndBorrow(Constants.MCD_JOIN_USDC_A, _cdpId); // Given, ETH price, calculate how much WETH we need to flashloan // Dividing by 2 to gives us 200% col ratio uint256 flashloanAmountWETH = mintAmountDAI.mul(1 ether).div( _ethUsdRatio18.div(2) ); require( IERC20(Constants.WETH).balanceOf(_solo) >= flashloanAmountWETH, "!weth-supply" ); // Wrap ETH into WETH WETH(Constants.WETH).deposit{value: msg.value}(); WETH(Constants.WETH).approve(_solo, flashloanAmountWETH.add(msg.value)); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, flashloanAmountWETH); operations[1] = _getCallAction( abi.encode( CSDParams({ mintAmountDAI: mintAmountDAI, withdrawAmountUSDC: withdrawAmountUSDC, flashloanAmountWETH: flashloanAmountWETH, cdpId: _cdpId, curvePool: _curvePool }) ) ); operations[2] = _getDepositAction( marketId, flashloanAmountWETH.add(msg.value) ); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); // Convert DAI leftovers to USDC uint256 daiBal = IERC20(Constants.DAI).balanceOf(address(this)); require( IERC20(Constants.DAI).approve(_curvePool, daiBal), "erc20-approve-curvepool-failed" ); ICurveFiCurve(_curvePool).exchange_underlying( int128(0), int128(1), daiBal, 0 ); // Refund leftovers IERC20(Constants.USDC).transfer( _sender, IERC20(Constants.USDC).balanceOf(address(this)) ); } } contract OpenShortDAI is ICallee, DydxFlashloanBase, DssActionsBase { // LeveragedShortDAI Params struct OSDParams { uint256 cdpId; // CDP Id to leverage uint256 mintAmountDAI; // Amount of DAI to mint uint256 flashloanAmountWETH; // Amount of WETH flashloaned address curvePool; } function callFunction( address sender, Account.Info memory account, bytes memory data ) public override { OSDParams memory osdp = abi.decode(data, (OSDParams)); // Step 1. Have Flashloaned WETH // Open WETH CDP in Maker, then Mint out some DAI uint256 wethCdp = _openLockGemAndDraw( Constants.MCD_JOIN_ETH_A, Constants.ETH_A_ILK, osdp.flashloanAmountWETH, osdp.mintAmountDAI ); // Step 2. // Converts Flashloaned DAI to USDC on CurveFi // DAI = 0 index, USDC = 1 index require( IERC20(Constants.DAI).approve(osdp.curvePool, osdp.mintAmountDAI), "!curvepool-approved" ); ICurveFiCurve(osdp.curvePool).exchange_underlying( int128(0), int128(1), osdp.mintAmountDAI, 0 ); // Step 3. // Locks up USDC and borrow just enough DAI to repay WETH CDP uint256 supplyAmount = IERC20(Constants.USDC).balanceOf(address(this)); _lockGemAndDraw( Constants.MCD_JOIN_USDC_A, osdp.cdpId, supplyAmount, osdp.mintAmountDAI ); // Step 4. // Repay DAI loan back to WETH CDP and FREE WETH _wipeAllAndFreeGem( Constants.MCD_JOIN_ETH_A, wethCdp, osdp.flashloanAmountWETH ); } function flashloanAndOpen( address _sender, address _solo, address _curvePool, uint256 _cdpId, uint256 _initialMarginUSDC, uint256 _mintAmountDAI, uint256 _flashloanAmountWETH ) external payable { require(msg.value == 2, "!fee"); require( IERC20(Constants.WETH).balanceOf(_solo) >= _flashloanAmountWETH, "!weth-supply" ); // Gets USDC require( IERC20(Constants.USDC).transferFrom( msg.sender, address(this), _initialMarginUSDC ), "initial-margin-transferFrom-failed" ); ISoloMargin solo = ISoloMargin(_solo); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(_solo, Constants.WETH); // Wrap ETH into WETH WETH(Constants.WETH).deposit{value: msg.value}(); WETH(Constants.WETH).approve( _solo, _flashloanAmountWETH.add(msg.value) ); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _flashloanAmountWETH); operations[1] = _getCallAction( // Encode OSDParams for callFunction abi.encode( OSDParams({ mintAmountDAI: _mintAmountDAI, flashloanAmountWETH: _flashloanAmountWETH, cdpId: _cdpId, curvePool: _curvePool }) ) ); operations[2] = _getDepositAction( marketId, _flashloanAmountWETH.add(msg.value) ); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); solo.operate(accountInfos, operations); // Refund user any ERC20 leftover IERC20(Constants.DAI).transfer( _sender, IERC20(Constants.DAI).balanceOf(address(this)) ); IERC20(Constants.USDC).transfer( _sender, IERC20(Constants.USDC).balanceOf(address(this)) ); } }
0x6080604052600436106100295760003560e01c806368cfb7231461002e5780638b41871314610043575b600080fd5b61004161003c36600461215c565b610063565b005b34801561004f57600080fd5b5061004161005e3660046121b6565b6106f7565b3460021461008c5760405162461bcd60e51b81526004016100839061262c565b60405180910390fd5b8360006100ad8273c02aaa39b223fe8d0a0e5c4f27ead9083c756cc261093b565b90506000806100d073a191e578a6736167326d05c119ce0c90849e84b787610a8c565b909250905060006100fd6100e5876002610f05565b6100f784670de0b6b3a7640000610f4e565b90610f05565b6040516370a0823160e01b8152909150819073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2906370a0823190610139908d906004016124b9565b60206040518083038186803b15801561015157600080fd5b505afa158015610165573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061018991906122b1565b10156101a75760405162461bcd60e51b81526004016100839061264a565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b1580156101f657600080fd5b505af115801561020a573d6000803e3d6000fd5b5073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2935063095ea7b392508c915061023890508434610f88565b6040518363ffffffff1660e01b81526004016102559291906124e7565b602060405180830381600087803b15801561026f57600080fd5b505af1158015610283573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102a79190612291565b5060408051600380825260808201909252606091816020015b6102c8612076565b8152602001906001900390816102c05790505090506102e78583610fad565b816000815181106102f457fe5b60200260200101819052506103566040518060a001604052808a81526020018b6001600160a01b03168152602001858152602001868152602001848152506040516020016103429190612752565b604051602081830303815290604052611037565b8160018151811061036357fe5b60209081029190910101526103818561037c8434610f88565b6110b3565b8160028151811061038e57fe5b6020908102919091010152604080516001808252818301909252606091816020015b6103b86120c8565b8152602001906001900390816103b05790505090506103d56110ee565b816000815181106103e257fe5b602090810291909101015260405163a67a6a4560e01b81526001600160a01b0388169063a67a6a459061041b9084908690600401612500565b600060405180830381600087803b15801561043557600080fd5b505af1158015610449573d6000803e3d6000fd5b50506040516370a0823160e01b815260009250736b175474e89094c44da98b954eedeac495271d0f91506370a08231906104879030906004016124b9565b60206040518083038186803b15801561049f57600080fd5b505afa1580156104b3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104d791906122b1565b60405163095ea7b360e01b8152909150736b175474e89094c44da98b954eedeac495271d0f9063095ea7b390610513908e9085906004016124e7565b602060405180830381600087803b15801561052d57600080fd5b505af1158015610541573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105659190612291565b6105815760405162461bcd60e51b8152600401610083906126f5565b604051635320bf6b60e11b81526001600160a01b038c169063a6417ed6906105b590600090600190869083906004016125bf565b600060405180830381600087803b1580156105cf57600080fd5b505af11580156105e3573d6000803e3d6000fd5b50506040516370a0823160e01b815273a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48925063a9059cbb91508f9083906370a08231906106289030906004016124b9565b60206040518083038186803b15801561064057600080fd5b505afa158015610654573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061067891906122b1565b6040518363ffffffff1660e01b81526004016106959291906124e7565b602060405180830381600087803b1580156106af57600080fd5b505af11580156106c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106e79190612291565b5050505050505050505050505050565b6106ff6120df565b8180602001905181019061071391906122c9565b90506000610747732f0b23f53734252bda2277357e97e1517d6b042a644554482d4160d81b8460800151856040015161110e565b905061077073a191e578a6736167326d05c119ce0c90849e84b7836000015184606001516111b2565b60208201516040516370a0823160e01b815260009073a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48906370a08231906107af9030906004016124b9565b60206040518083038186803b1580156107c757600080fd5b505afa1580156107db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107ff91906122b1565b60405163095ea7b360e01b815290915073a0b86991c6218b36c1d19d4a2e9eb0ce3606eb489063095ea7b39061083b90859085906004016124e7565b602060405180830381600087803b15801561085557600080fd5b505af1158015610869573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061088d9190612291565b6108a95760405162461bcd60e51b8152600401610083906126f5565b604051635320bf6b60e11b81526001600160a01b0383169063a6417ed6906108dd90600190600090869082906004016125bf565b600060405180830381600087803b1580156108f757600080fd5b505af115801561090b573d6000803e3d6000fd5b50505050610932732f0b23f53734252bda2277357e97e1517d6b042a8486608001516111b2565b50505050505050565b6000808390506000816001600160a01b031663295c39a56040518163ffffffff1660e01b815260040160206040518083038186803b15801561097c57600080fd5b505afa158015610990573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109b491906122b1565b90506000805b82811015610a6d5760405163062bd3e960e01b81526001600160a01b0385169063062bd3e9906109ee90849060040161259f565b60206040518083038186803b158015610a0657600080fd5b505afa158015610a1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a3e9190612140565b9150856001600160a01b0316826001600160a01b03161415610a65579350610a8692505050565b6001016109ba565b5060405162461bcd60e51b8152600401610083906126b1565b92915050565b6000806000735ef30b9986345249bc32d8928b7ee64de9435e3990506000816001600160a01b03166336569e776040518163ffffffff1660e01b815260040160206040518083038186803b158015610ae357600080fd5b505afa158015610af7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b1b9190612140565b90506000826001600160a01b0316632c2cb9fd876040518263ffffffff1660e01b8152600401610b4b919061259f565b60206040518083038186803b158015610b6357600080fd5b505afa158015610b77573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b9b91906122b1565b90506000826001600160a01b031663d9638d36836040518263ffffffff1660e01b8152600401610bcb919061259f565b60a06040518083038186803b158015610be357600080fd5b505afa158015610bf7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c1b9190612348565b505050915050600080846001600160a01b0316632424be5c85886001600160a01b0316632726b0738d6040518263ffffffff1660e01b8152600401610c60919061259f565b60206040518083038186803b158015610c7857600080fd5b505afa158015610c8c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cb09190612140565b6040518363ffffffff1660e01b8152600401610ccd9291906125a8565b604080518083038186803b158015610ce457600080fd5b505afa158015610cf8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d1c9190612325565b915091506000856001600160a01b0316636c25b346886001600160a01b0316638161b1208d6040518263ffffffff1660e01b8152600401610d5d919061259f565b60206040518083038186803b158015610d7557600080fd5b505afa158015610d89573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dad9190612140565b6040518263ffffffff1660e01b8152600401610dc991906124b9565b60206040518083038186803b158015610de157600080fd5b505afa158015610df5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e1991906122b1565b90506000610e3182610e2b8588610f4e565b90611537565b90506000676765c793fa10079d601b1b82049050600082610e5d83676765c793fa10079d601b1b610f4e565b10610e685781610e6d565b816001015b9050610ef28e6001600160a01b031663b3bcfa826040518163ffffffff1660e01b8152600401602060405180830381600087803b158015610ead57600080fd5b505af1158015610ec1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ee591906122b1565b8790601203600a0a610f05565b9e909d509b505050505050505050505050565b6000610f4783836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611579565b9392505050565b600082610f5d57506000610a86565b82820282848281610f6a57fe5b0414610f475760405162461bcd60e51b815260040161008390612670565b600082820183811015610f475760405162461bcd60e51b8152600401610083906125f5565b610fb5612076565b604080516101008101825260018152600060208083018290528351608081018552828152929384019291908201905b81526020016000815260200185815250815260200184815260200160008152602001306001600160a01b031681526020016000815260200160405180602001604052806000815250815250905092915050565b61103f612076565b60408051610100810182526008815260006020808301829052835160808101855282815292938401929190820190815260200160008152602001600081525081526020016000815260200160008152602001306001600160a01b03168152602001600081526020018381525090505b919050565b6110bb612076565b60408051610100810182526000808252602080830182905283516080810185526001815292938401929190820190610fe4565b6110f66120c8565b50604080518082019091523081526001602082015290565b604051636090dec560e01b8152600090735ef30b9986345249bc32d8928b7ee64de9435e3990636090dec59061114a90879030906004016125a8565b602060405180830381600087803b15801561116457600080fd5b505af1158015611178573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061119c91906122b1565b90506111aa858285856115b0565b949350505050565b6000735ef30b9986345249bc32d8928b7ee64de9435e3990506000816001600160a01b03166336569e776040518163ffffffff1660e01b815260040160206040518083038186803b15801561120657600080fd5b505afa15801561121a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061123e9190612140565b90506000826001600160a01b0316632726b073866040518263ffffffff1660e01b815260040161126e919061259f565b60206040518083038186803b15801561128657600080fd5b505afa15801561129a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112be9190612140565b90506000836001600160a01b0316632c2cb9fd876040518263ffffffff1660e01b81526004016112ee919061259f565b60206040518083038186803b15801561130657600080fd5b505afa15801561131a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061133e91906122b1565b90506000836001600160a01b0316632424be5c83856040518363ffffffff1660e01b81526004016113709291906125a8565b604080518083038186803b15801561138757600080fd5b505afa15801561139b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113bf9190612325565b9150506113ec739759a6ac90977b93b58547b4a71c78317f391a28846113e7878788886119bb565b611b97565b60006113f88988611cc5565b9050856001600160a01b03166345e6bdcd8961141384611d4a565b600003856000036040518463ffffffff1660e01b8152600401611438939291906127af565b600060405180830381600087803b15801561145257600080fd5b505af1158015611466573d6000803e3d6000fd5b50506040516313771f0760e31b81526001600160a01b0389169250639bb8f838915061149a908b9030908690600401612790565b600060405180830381600087803b1580156114b457600080fd5b505af11580156114c8573d6000803e3d6000fd5b505060405163ef693bed60e01b81526001600160a01b038c16925063ef693bed91506114fa9030908b906004016124e7565b600060405180830381600087803b15801561151457600080fd5b505af1158015611528573d6000803e3d6000fd5b50505050505050505050505050565b6000610f4783836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611d6c565b6000818361159a5760405162461bcd60e51b815260040161008391906125e2565b5060008385816115a657fe5b0495945050505050565b604051632726b07360e01b8152735ef30b9986345249bc32d8928b7ee64de9435e39906000908290632726b073906115ec90889060040161259f565b60206040518083038186803b15801561160457600080fd5b505afa158015611618573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061163c9190612140565b90506000826001600160a01b03166336569e776040518163ffffffff1660e01b815260040160206040518083038186803b15801561167957600080fd5b505afa15801561168d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116b19190612140565b90506000836001600160a01b0316632c2cb9fd886040518263ffffffff1660e01b81526004016116e1919061259f565b60206040518083038186803b1580156116f957600080fd5b505afa15801561170d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061173191906122b1565b90506117408884886001611d98565b836001600160a01b03166345e6bdcd8861176261175d8c8b611cc5565b611d4a565b611783867319c0976f590d67707e62397c87829d896dc0f1f189888d611ed7565b6040518463ffffffff1660e01b81526004016117a1939291906127af565b600060405180830381600087803b1580156117bb57600080fd5b505af11580156117cf573d6000803e3d6000fd5b50505050836001600160a01b031663f9f30db688306117ed8961205f565b6040518463ffffffff1660e01b815260040161180b93929190612790565b600060405180830381600087803b15801561182557600080fd5b505af1158015611839573d6000803e3d6000fd5b5050604051634538c4eb60e01b81526001600160a01b0385169250634538c4eb915061187f903090739759a6ac90977b93b58547b4a71c78317f391a28906004016124cd565b60206040518083038186803b15801561189757600080fd5b505afa1580156118ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118cf91906122b1565b611946576040516328ec8bf160e21b81526001600160a01b0383169063a3b22fc49061191390739759a6ac90977b93b58547b4a71c78317f391a28906004016124b9565b600060405180830381600087803b15801561192d57600080fd5b505af1158015611941573d6000803e3d6000fd5b505050505b60405163ef693bed60e01b8152739759a6ac90977b93b58547b4a71c78317f391a289063ef693bed9061197f90309089906004016124e7565b600060405180830381600087803b15801561199957600080fd5b505af11580156119ad573d6000803e3d6000fd5b505050505050505050505050565b600080856001600160a01b031663d9638d36846040518263ffffffff1660e01b81526004016119ea919061259f565b60a06040518083038186803b158015611a0257600080fd5b505afa158015611a16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a3a9190612348565b5050509150506000866001600160a01b0316632424be5c85876040518363ffffffff1660e01b8152600401611a709291906125a8565b604080518083038186803b158015611a8757600080fd5b505afa158015611a9b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611abf9190612325565b9150506000876001600160a01b0316636c25b346886040518263ffffffff1660e01b8152600401611af091906124b9565b60206040518083038186803b158015611b0857600080fd5b505afa158015611b1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b4091906122b1565b90506000611b5282610e2b8587610f4e565b9050676765c793fa10079d601b1b8104945080611b7a86676765c793fa10079d601b1b610f4e565b10611b855784611b8a565b846001015b9998505050505050505050565b826001600160a01b031663f4b9fa756040518163ffffffff1660e01b8152600401602060405180830381600087803b158015611bd257600080fd5b505af1158015611be6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c0a9190612140565b6001600160a01b031663095ea7b384836040518363ffffffff1660e01b8152600401611c379291906124e7565b600060405180830381600087803b158015611c5157600080fd5b505af1158015611c65573d6000803e3d6000fd5b5050604051633b4da69f60e01b81526001600160a01b0386169250633b4da69f9150611c9790859085906004016124e7565b600060405180830381600087803b158015611cb157600080fd5b505af1158015610932573d6000803e3d6000fd5b6000610f47836001600160a01b031663b3bcfa826040518163ffffffff1660e01b8152600401602060405180830381600087803b158015611d0557600080fd5b505af1158015611d19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d3d91906122b1565b8390601203600a0a610f4e565b8060008112156110ae5760405162461bcd60e51b81526004016100839061272c565b60008184841115611d905760405162461bcd60e51b815260040161008391906125e2565b505050900390565b8015611e7157836001600160a01b0316637bd2bea76040518163ffffffff1660e01b8152600401602060405180830381600087803b158015611dd957600080fd5b505af1158015611ded573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e119190612140565b6001600160a01b031663095ea7b385846040518363ffffffff1660e01b8152600401611e3e9291906124e7565b600060405180830381600087803b158015611e5857600080fd5b505af1158015611e6c573d6000803e3d6000fd5b505050505b604051633b4da69f60e01b81526001600160a01b03851690633b4da69f90611e9f90869086906004016124e7565b600060405180830381600087803b158015611eb957600080fd5b505af1158015611ecd573d6000803e3d6000fd5b5050505050505050565b600080856001600160a01b03166344e2a5a8856040518263ffffffff1660e01b8152600401611f06919061259f565b602060405180830381600087803b158015611f2057600080fd5b505af1158015611f34573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f5891906122b1565b90506000876001600160a01b0316636c25b346876040518263ffffffff1660e01b8152600401611f8891906124b9565b60206040518083038186803b158015611fa057600080fd5b505afa158015611fb4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fd891906122b1565b9050611fef84676765c793fa10079d601b1b610f4e565b811015612054576120208261201383610e2b88676765c793fa10079d601b1b610f4e565b8161201a57fe5b04611d4a565b925061203784676765c793fa10079d601b1b610f4e565b6120418484610f4e565b1061204c5782612051565b826001015b92505b505095945050505050565b6000610a8682676765c793fa10079d601b1b610f4e565b604080516101008101825260008082526020820152908101612096612117565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b604080518082019091526000808252602082015290565b6040518060a001604052806000815260200160006001600160a01b031681526020016000815260200160008152602001600081525090565b604080516080810190915260008082526020820190815260200160008152602001600081525090565b600060208284031215612151578081fd5b8151610f47816127f9565b600080600080600060a08688031215612173578081fd5b853561217e816127f9565b9450602086013561218e816127f9565b9350604086013561219e816127f9565b94979396509394606081013594506080013592915050565b600080600083850360808112156121cb578384fd5b84356121d6816127f9565b93506020601f19604083820112156121ec578485fd5b6121f660406127c5565b925081870135612205816127f9565b835260408701358284015291935060608601359167ffffffffffffffff8084111561222e578485fd5b838801935088601f850112612241578485fd5b83358181111561224f578586fd5b61225f8484601f840116016127c5565b92508083528984828701011115612274578586fd5b808486018585013782019092019390935250929591945092509050565b6000602082840312156122a2578081fd5b81518015158114610f47578182fd5b6000602082840312156122c2578081fd5b5051919050565b600060a082840312156122da578081fd5b6122e460a06127c5565b8251815260208301516122f6816127f9565b806020830152506040830151604082015260608301516060820152608083015160808201528091505092915050565b60008060408385031215612337578182fd5b505080516020909101519092909150565b600080600080600060a0868803121561235f578081fd5b5050835160208501516040860151606087015160809097015192989197509594509092509050565b80516001600160a01b031682526020908101519082015260400190565b6001600160a01b03169052565b60008151808452815b818110156123d6576020818501810151868301820152016123ba565b818111156123e75782602083870101525b50601f01601f19169290920160200192915050565b600061016082516009811061240d57fe5b8085525060208301516020850152604083015161242d6040860182612482565b50606083015160c0850152608083015160e085015260a08301516124556101008601826123a4565b5060c083015161012085015260e083015181610140860152612479828601826123b1565b95945050505050565b8051151582526020810151612496816127ec565b602083015260408101516124a9816127ec565b6040830152606090810151910152565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03929092168252602082015260400190565b60006040820160408352808551612517818461259f565b915060209250828701845b8281101561254357612535848351612387565b935090840190600101612522565b5050508381038285015284518082528282019080840283018401878501865b8381101561259057601f1986840301855261257e8383516123fc565b94870194925090860190600101612562565b50909998505050505050505050565b90815260200190565b9182526001600160a01b0316602082015260400190565b600f94850b81529290930b60208301526040820152606081019190915260800190565b600060208252610f4760208301846123b1565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252600490820152632166656560e01b604082015260600190565b6020808252600c908201526b21776574682d737570706c7960a01b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526024908201527f4e6f206d61726b6574496420666f756e6420666f722070726f7669646564207460408201526337b5b2b760e11b606082015260800190565b6020808252601e908201527f65726332302d617070726f76652d6375727665706f6f6c2d6661696c65640000604082015260600190565b6020808252600c908201526b696e742d6f766572666c6f7760a01b604082015260600190565b815181526020808301516001600160a01b03169082015260408083015190820152606080830151908201526080918201519181019190915260a00190565b9283526001600160a01b03919091166020830152604082015260600190565b9283526020830191909152604082015260600190565b60405181810167ffffffffffffffff811182821017156127e457600080fd5b604052919050565b600281106127f657fe5b50565b6001600160a01b03811681146127f657600080fdfea2646970667358221220739eccd1bdb7705acb4cb032ff126c69e48376b8ce129d3d642d5c1fd4fb45f164736f6c634300060c0033
[ 5, 16, 4, 17 ]
0x419aF1fcFa2Ce803686299b2EB784f91d20e9eA5
pragma solidity 0.6.6; abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; return msg.data; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } 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) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ERC20 is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; bool private _isTransferable = false; address private _crowdAddress; address private _racerAddress; address private _poolRewardAddress; constructor(string memory name, string memory symbol, uint256 amount) public { _name = name; _symbol = symbol; _decimals = 18; _totalSupply = amount * 10 ** uint256(_decimals); _balances[owner()] = _totalSupply; } 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 override view returns (uint256) { return _totalSupply; } function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public virtual override view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(_isTransferable || sender == owner()); require(sender != _poolRewardAddress); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _setPoolRewardAddress( address poolRewardAddress ) internal { _poolRewardAddress = poolRewardAddress; } function _setRacerAddress( address contractAddress ) internal { _racerAddress = contractAddress; } function _setCrowdAddress( address contractAddress ) internal { _crowdAddress = contractAddress; } function _purchase( address recipient, uint256 amount ) internal { require(msg.sender == _crowdAddress); _transfer(owner(), recipient, amount); } function _transferReward( address recipient, uint256 amount ) internal { require(msg.sender == _racerAddress); _beforeTokenTransfer(_poolRewardAddress, recipient, amount); _balances[_poolRewardAddress] = _balances[_poolRewardAddress].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(_poolRewardAddress, recipient, amount); } function _setTransferable( uint8 _value ) internal { if (_value == 0) { _isTransferable = false; } if (_value == 1) { _isTransferable = true; } } } contract TortoToken is ERC20("Tortoise.Finance", "TRTF", 1000000) { function transferReward(address recipient, uint256 amount) public returns (bool) { _transferReward(recipient, amount); return true; } function setPoolRewardAddress(address poolRewardAddress) public onlyOwner returns (bool) { _setPoolRewardAddress(poolRewardAddress); return true; } function setRacerAddress(address contractAddress) public onlyOwner returns (bool) { _setRacerAddress(contractAddress); return true; } function setCrowdAddress(address contractAddress) public onlyOwner returns (bool) { _setCrowdAddress(contractAddress); return true; } function purchase(address recipient, uint256 amount) public returns (bool) { _purchase(recipient, amount); return true; } function setTransferable(uint8 _value) public onlyOwner virtual { _setTransferable(_value); } } contract Crowdsale is Ownable { using SafeMath for uint256; using Address for address; TortoToken private token; uint256 public cap = 500 ether; address payable private wallet; uint256 public rate = 500; uint256 public minContribution = 0.5 ether; uint256 public maxContribution = 5 ether; uint256 public weiRaised; mapping (address => uint256) public contributions; bool public isCrowdsaleFinalized = false; event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function CrowdsaleStarter(TortoToken _token) public onlyOwner { token = _token; wallet = address(uint160(owner())); } receive () external payable { purchaseTokens(msg.sender); } function purchaseTokens(address recipient) public payable { require(recipient != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 amount = getTokenAmount(weiAmount); weiAmount = weiRaised.add(weiAmount); contributions[recipient] = contributions[recipient].add(weiAmount); token.purchase(recipient, amount); emit TokenPurchase(msg.sender, recipient, weiAmount, amount); wallet.transfer(msg.value); } function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return capReached || isCrowdsaleFinalized; } function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { uint256 tokens = weiAmount.mul(rate); return tokens; } function validPurchase() internal view returns (bool) { require(weiRaised.add(msg.value) <= cap); bool moreThanMinPurchase = msg.value >= minContribution; bool lessThanMaxPurchase = contributions[msg.sender] + msg.value <= maxContribution; return moreThanMinPurchase && lessThanMaxPurchase && !isCrowdsaleFinalized; } function finalizeCrowdsale() public onlyOwner { isCrowdsaleFinalized = true; } }
0x6080604052600436106100e15760003560e01c80637d81dcee1161007f578063aaffadf311610059578063aaffadf314610246578063ce5570311461025b578063ecb70fb714610281578063f2fde38b14610296576100f1565b80637d81dcee146101cd5780638d3d6576146102005780638da5cb5b14610215576100f1565b8063355274ea116100bb578063355274ea1461015b5780634042b66f1461017057806342e94c9014610185578063715018a6146101b8576100f1565b80630bf318a3146100f65780632c4e722e1461010b578063349b586c14610132576100f1565b366100f1576100ef336102c9565b005b600080fd5b34801561010257600080fd5b506100ef610458565b34801561011757600080fd5b506101206104bf565b60408051918252519081900360200190f35b34801561013e57600080fd5b506101476104c5565b604080519115158252519081900360200190f35b34801561016757600080fd5b506101206104ce565b34801561017c57600080fd5b506101206104d4565b34801561019157600080fd5b50610120600480360360208110156101a857600080fd5b50356001600160a01b03166104da565b3480156101c457600080fd5b506100ef6104ec565b3480156101d957600080fd5b506100ef600480360360208110156101f057600080fd5b50356001600160a01b031661058e565b34801561020c57600080fd5b5061012061062c565b34801561022157600080fd5b5061022a610632565b604080516001600160a01b039092168252519081900360200190f35b34801561025257600080fd5b50610120610641565b6100ef6004803603602081101561027157600080fd5b50356001600160a01b03166102c9565b34801561028d57600080fd5b50610147610647565b3480156102a257600080fd5b506100ef600480360360208110156102b957600080fd5b50356001600160a01b0316610666565b6001600160a01b0381166102dc57600080fd5b6102e461075e565b6102ed57600080fd5b3460006102f9826107c8565b60075490915061030f908363ffffffff6107e716565b6001600160a01b03841660009081526008602052604090205490925061033b908363ffffffff6107e716565b6001600160a01b0380851660008181526008602090815260408083209590955560015485516346f4991160e11b815260048101949094526024840187905294519490931693638de93222936044808501949193918390030190829087803b1580156103a557600080fd5b505af11580156103b9573d6000803e3d6000fd5b505050506040513d60208110156103cf57600080fd5b5050604080518381526020810183905281516001600160a01b0386169233927f623b3804fa71d67900d064613da8f94b9617215ee90799290593e1745087ad18929081900390910190a36003546040516001600160a01b03909116903480156108fc02916000818181858888f19350505050158015610452573d6000803e3d6000fd5b50505050565b61046061084a565b6000546001600160a01b039081169116146104b0576040805162461bcd60e51b815260206004820181905260248201526000805160206108ef833981519152604482015290519081900360640190fd5b6009805460ff19166001179055565b60045481565b60095460ff1681565b60025481565b60075481565b60086020526000908152604090205481565b6104f461084a565b6000546001600160a01b03908116911614610544576040805162461bcd60e51b815260206004820181905260248201526000805160206108ef833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b61059661084a565b6000546001600160a01b039081169116146105e6576040805162461bcd60e51b815260206004820181905260248201526000805160206108ef833981519152604482015290519081900360640190fd5b600180546001600160a01b0319166001600160a01b038316179055610609610632565b600380546001600160a01b0319166001600160a01b039290921691909117905550565b60065481565b6000546001600160a01b031690565b60055481565b60025460075460009111158080610660575060095460ff165b91505090565b61066e61084a565b6000546001600160a01b039081169116146106be576040805162461bcd60e51b815260206004820181905260248201526000805160206108ef833981519152604482015290519081900360640190fd5b6001600160a01b0381166107035760405162461bcd60e51b81526004018080602001828103825260268152602001806108a86026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000600254610778346007546107e790919063ffffffff16565b111561078357600080fd5b600554600654336000908152600860205260409020543492831080159390910191909111159082906107b25750805b80156107c1575060095460ff16155b9250505090565b6000806107e06004548461084e90919063ffffffff16565b9392505050565b600082820183811015610841576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b90505b92915050565b3390565b60008261085d57506000610844565b8282028284828161086a57fe5b04146108415760405162461bcd60e51b81526004018080602001828103825260218152602001806108ce6021913960400191505060405180910390fdfe4f776e61626c653a206e6577206f776e657220697320746865207a65726f2061646472657373536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f774f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572a26469706673582212208f770a2c5822a4bf0cdef13bdd43a760e8d4452bd7160dd26a58a311149a88c864736f6c63430006060033
[ 0, 5 ]
0x419D48fFc4Cf75Ecaf4f87322eEcccc386A17C53
pragma solidity 0.5.17; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract StubToken is ERC20, ERC20Detailed { constructor(string memory name, string memory symbol, uint256 initialSupply) public ERC20Detailed(name, symbol, 18) { _mint(msg.sender, initialSupply); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b6106778560405180606001604052806028815260200161101660289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e629092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2290919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161108760259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e629092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110636024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fce6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061103e6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fab6023913960400191505060405180910390fd5b610d2381604051806060016040528060268152602001610ff0602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e629092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610db6816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2290919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f0f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610ed4578082015181840152602081019050610eb9565b50505050905090810190601f168015610f015780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fa0576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b809150509291505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a72315820edd81728d825a79e4b15c6189abf323d7dc7b2a93601f16031c18571e260c7fb64736f6c63430005110032
[ 38 ]
0x42c015dc28ec39c8aa6bdfa777027d3acb03fb8c
pragma solidity 0.5.7; 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; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20Standard { using SafeMath for uint256; uint public totalSupply; string public name; uint8 public decimals; string public symbol; string public version; mapping (address => uint256) balances; mapping (address => mapping (address => uint)) allowed; //Fix for short address attack against ERC20 modifier onlyPayloadSize(uint size) { assert(msg.data.length == size + 4); _; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } function transfer(address _recipient, uint _value) public onlyPayloadSize(2*32) { require(balances[msg.sender] >= _value && _value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_recipient] = balances[_recipient].add(_value); emit Transfer(msg.sender, _recipient, _value); } function transferFrom(address _from, address _to, uint _value) public { require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); } function approve(address _spender, uint _value) public { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); } function allowance(address _spender, address _owner) public view returns (uint balance) { return allowed[_owner][_spender]; } //Event which is triggered to log all transfers to this contract's event log event Transfer( address indexed _from, address indexed _to, uint _value ); //Event which is triggered whenever an owner approves a new allowance for a spender. event Approval( address indexed _owner, address indexed _spender, uint _value ); } contract Token is ERC20Standard { constructor() public { totalSupply = 10000000000000; name = "BMW"; decimals = 6; symbol = "BMW"; version = "1.0"; balances[msg.sender] = totalSupply; } }
0x608060405234801561001057600080fd5b506004361061009e5760003560e01c806354fd4d501161006657806354fd4d501461022457806370a08231146102a757806395d89b41146102ff578063a9059cbb14610382578063dd62ed3e146103d05761009e565b806306fdde03146100a3578063095ea7b31461012657806318160ddd1461017457806323b872dd14610192578063313ce56714610200575b600080fd5b6100ab610448565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100eb5780820151818401526020810190506100d0565b50505050905090810190601f1680156101185780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101726004803603604081101561013c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506104e6565b005b61017c6105d0565b6040518082815260200191505060405180910390f35b6101fe600480360360608110156101a857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105d6565b005b610208610959565b604051808260ff1660ff16815260200191505060405180910390f35b61022c61096c565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561026c578082015181840152602081019050610251565b50505050905090810190601f1680156102995780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102e9600480360360208110156102bd57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610a0a565b6040518082815260200191505060405180910390f35b610307610a53565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561034757808201518184015260208101905061032c565b50505050905090810190601f1680156103745780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ce6004803603604081101561039857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610af1565b005b610432600480360360408110156103e657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610cef565b6040518082815260200191505060405180910390f35b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104de5780601f106104b3576101008083540402835291602001916104de565b820191906000526020600020905b8154815290600101906020018083116104c157829003601f168201915b505050505081565b80600660003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a35050565b60005481565b80600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101580156106a1575080600660008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410155b80156106ad5750600081115b6106b657600080fd5b61070881600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610d7690919063ffffffff16565b600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061079d81600560008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610d9590919063ffffffff16565b600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061086f81600660008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610d9590919063ffffffff16565b600660008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b600260009054906101000a900460ff1681565b60048054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a025780601f106109d757610100808354040283529160200191610a02565b820191906000526020600020905b8154815290600101906020018083116109e557829003601f168201915b505050505081565b6000600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60038054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610ae95780601f10610abe57610100808354040283529160200191610ae9565b820191906000526020600020905b815481529060010190602001808311610acc57829003601f168201915b505050505081565b604060048101600036905014610b0357fe5b81600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410158015610b525750600082115b610b5b57600080fd5b610bad82600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610d9590919063ffffffff16565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610c4282600560008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610d7690919063ffffffff16565b600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3505050565b6000600660008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600080828401905083811015610d8b57600080fd5b8091505092915050565b600082821115610da457600080fd5b60008284039050809150509291505056fea165627a7a72305820abd9600fe9b9ed28c7c576aa91324ddb12de8677c33c38792a73f29d5dd507fb0029
[ 17 ]
0x42EaA6F456Ce8ee9292C0fdD9af40C389CAB48b0
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ERC20 { function totalSupply() external view returns (uint); function decimals() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); } library GuardianUtils { /** * @notice Checks if an address is a guardian or an account authorised to sign on behalf of a smart-contract guardian * given a list of guardians. * @param _guardians the list of guardians * @param _guardian the address to test * @return true and the list of guardians minus the found guardian upon success, false and the original list of guardians if not found. */ function isGuardianOrGuardianSigner(address[] memory _guardians, address _guardian) internal view returns (bool, address[] memory) { if (_guardians.length == 0 || _guardian == address(0)) { return (false, _guardians); } bool isFound = false; address[] memory updatedGuardians = new address[](_guardians.length - 1); uint256 index = 0; for (uint256 i = 0; i < _guardians.length; i++) { if (!isFound) { // check if _guardian is an account guardian if (_guardian == _guardians[i]) { isFound = true; continue; } // check if _guardian is the owner of a smart contract guardian if (isContract(_guardians[i]) && isGuardianOwner(_guardians[i], _guardian)) { isFound = true; continue; } } if (index < updatedGuardians.length) { updatedGuardians[index] = _guardians[i]; index++; } } return isFound ? (true, updatedGuardians) : (false, _guardians); } /** * @notice Checks if an address is a contract. * @param _addr The address. */ function isContract(address _addr) internal view returns (bool) { uint32 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_addr) } return (size > 0); } /** * @notice Checks if an address is the owner of a guardian contract. * The method does not revert if the call to the owner() method consumes more then 5000 gas. * @param _guardian The guardian contract * @param _owner The owner to verify. */ function isGuardianOwner(address _guardian, address _owner) internal view returns (bool) { address owner = address(0); bytes4 sig = bytes4(keccak256("owner()")); // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr,sig) let result := staticcall(5000, _guardian, ptr, 0x20, ptr, 0x20) if eq(result, 1) { owner := mload(ptr) } } return owner == _owner; } } interface IFeature { enum OwnerSignature { Anyone, // Anyone Required, // Owner required Optional, // Owner and/or guardians Disallowed // guardians only } /** * @notice Utility method to recover any ERC20 token that was sent to the Feature by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; /** * @notice Inits a Feature for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(address _wallet) external; /** * @notice Helper method to check if an address is an authorised feature of a target wallet. * @param _wallet The target wallet. * @param _feature The address. */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) external view returns (bool); /** * @notice Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures and the wallet owner signature requirement. */ function getRequiredSignatures(address _wallet, bytes calldata _data) external view returns (uint256, OwnerSignature); /** * @notice Gets the list of static call signatures that this feature responds to on behalf of wallets */ function getStaticCallSignatures() external view returns (bytes4[] memory); } interface IGuardianStorage { /** * @notice Lets an authorised module add a guardian to a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(address _wallet, address _guardian) external; /** * @notice Lets an authorised module revoke a guardian from a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(address _wallet, address _guardian) external; /** * @notice Checks if an account is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The account. * @return true if the account is a guardian for a wallet. */ function isGuardian(address _wallet, address _guardian) external view returns (bool); function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, uint256 _releaseAfter) external; function getGuardians(address _wallet) external view returns (address[] memory); function guardianCount(address _wallet) external view returns (uint256); } interface ILimitStorage { struct Limit { // the current limit uint128 current; // the pending limit if any uint128 pending; // when the pending limit becomes the current limit uint64 changeAfter; } struct DailySpent { // The amount already spent during the current period uint128 alreadySpent; // The end of the current period uint64 periodEnd; } function setLimit(address _wallet, Limit memory _limit) external; function getLimit(address _wallet) external view returns (Limit memory _limit); function setDailySpent(address _wallet, DailySpent memory _dailySpent) external; function getDailySpent(address _wallet) external view returns (DailySpent memory _dailySpent); function setLimitAndDailySpent(address _wallet, Limit memory _limit, DailySpent memory _dailySpent) external; function getLimitAndDailySpent(address _wallet) external view returns (Limit memory _limit, DailySpent memory _dailySpent); } interface ILockStorage { function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, address _locker, uint256 _releaseAfter) external; } interface IModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } interface IVersionManager { /** * @notice Returns true if the feature is authorised for the wallet * @param _wallet The target wallet. * @param _feature The feature. */ function isFeatureAuthorised(address _wallet, address _feature) external view returns (bool); /** * @notice Lets a feature (caller) invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function checkAuthorisedFeatureAndInvokeWallet( address _wallet, address _to, uint256 _value, bytes calldata _data ) external returns (bytes memory _res); /* ******* Backward Compatibility with old Storages and BaseWallet *************** */ /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _wallet, address _newOwner) external; /** * @notice Lets a feature write data to a storage contract. * @param _wallet The target wallet. * @param _storage The storage contract. * @param _data The data of the call */ function invokeStorage(address _wallet, address _storage, bytes calldata _data) external; /** * @notice Upgrade a wallet to a new version. * @param _wallet the wallet to upgrade * @param _toVersion the new version */ function upgradeWallet(address _wallet, uint256 _toVersion) external; } interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract BaseFeature is IFeature { // Empty calldata bytes constant internal EMPTY_BYTES = ""; // Mock token address for ETH address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // The address of the Lock storage ILockStorage internal lockStorage; // The address of the Version Manager IVersionManager internal versionManager; event FeatureCreated(bytes32 name); /** * @notice Throws if the wallet is locked. */ modifier onlyWhenUnlocked(address _wallet) { require(!lockStorage.isLocked(_wallet), "BF: wallet locked"); _; } /** * @notice Throws if the sender is not the VersionManager. */ modifier onlyVersionManager() { require(msg.sender == address(versionManager), "BF: caller must be VersionManager"); _; } /** * @notice Throws if the sender is not the owner of the target wallet. */ modifier onlyWalletOwner(address _wallet) { require(isOwner(_wallet, msg.sender), "BF: must be wallet owner"); _; } /** * @notice Throws if the sender is not an authorised feature of the target wallet. */ modifier onlyWalletFeature(address _wallet) { require(versionManager.isFeatureAuthorised(_wallet, msg.sender), "BF: must be a wallet feature"); _; } /** * @notice Throws if the sender is not the owner of the target wallet or the feature itself. */ modifier onlyWalletOwnerOrFeature(address _wallet) { // Wrapping in an internal method reduces deployment cost by avoiding duplication of inlined code verifyOwnerOrAuthorisedFeature(_wallet, msg.sender); _; } constructor( ILockStorage _lockStorage, IVersionManager _versionManager, bytes32 _name ) public { lockStorage = _lockStorage; versionManager = _versionManager; emit FeatureCreated(_name); } /** * @inheritdoc IFeature */ function recoverToken(address _token) external virtual override { uint total = ERC20(_token).balanceOf(address(this)); _token.call(abi.encodeWithSelector(ERC20(_token).transfer.selector, address(versionManager), total)); } /** * @notice Inits the feature for a wallet by doing nothing. * @dev !! Overriding methods need make sure `init()` can only be called by the VersionManager !! * @param _wallet The wallet. */ function init(address _wallet) external virtual override {} /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external virtual view override returns (uint256, OwnerSignature) { revert("BF: disabled method"); } /** * @inheritdoc IFeature */ function getStaticCallSignatures() external virtual override view returns (bytes4[] memory _sigs) {} /** * @inheritdoc IFeature */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) public override view returns (bool) { return versionManager.isFeatureAuthorised(_wallet, _feature); } /** * @notice Checks that the wallet address provided as the first parameter of _data matches _wallet * @return false if the addresses are different. */ function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet = abi.decode(_data[4:], (address)); return dataWallet == _wallet; } /** * @notice Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(address _wallet, address _addr) internal view returns (bool) { return IWallet(_wallet).owner() == _addr; } /** * @notice Verify that the caller is an authorised feature or the wallet owner. * @param _wallet The target wallet. * @param _sender The caller. */ function verifyOwnerOrAuthorisedFeature(address _wallet, address _sender) internal view { require(isFeatureAuthorisedInVersionManager(_wallet, _sender) || isOwner(_wallet, _sender), "BF: must be owner or feature"); } /** * @notice Helper method to invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) { _res = versionManager.checkAuthorisedFeatureAndInvokeWallet(_wallet, _to, _value, _data); } } contract LockManager is BaseFeature { bytes32 constant NAME = "LockManager"; // The lock period uint256 public lockPeriod; // the guardian storage IGuardianStorage public guardianStorage; // *************** Events *************************** // event Locked(address indexed wallet, uint64 releaseAfter); event Unlocked(address indexed wallet); // *************** Modifiers ************************ // /** * @notice Throws if the wallet is not locked. */ modifier onlyWhenLocked(address _wallet) { require(lockStorage.isLocked(_wallet), "LM: wallet must be locked"); _; } /** * @notice Throws if the caller is not a guardian for the wallet. */ modifier onlyGuardianOrFeature(address _wallet) { bool isGuardian = guardianStorage.isGuardian(_wallet, msg.sender); require(isFeatureAuthorisedInVersionManager(_wallet, msg.sender) || isGuardian, "LM: must be guardian or feature"); _; } // *************** Constructor ************************ // constructor( ILockStorage _lockStorage, IGuardianStorage _guardianStorage, IVersionManager _versionManager, uint256 _lockPeriod ) BaseFeature(_lockStorage, _versionManager, NAME) public { guardianStorage = _guardianStorage; lockPeriod = _lockPeriod; } // *************** External functions ************************ // /** * @notice Lets a guardian lock a wallet. * @param _wallet The target wallet. */ function lock(address _wallet) external onlyGuardianOrFeature(_wallet) onlyWhenUnlocked(_wallet) { setLock(_wallet, block.timestamp + lockPeriod); emit Locked(_wallet, uint64(block.timestamp + lockPeriod)); } /** * @notice Lets a guardian unlock a locked wallet. * @param _wallet The target wallet. */ function unlock(address _wallet) external onlyGuardianOrFeature(_wallet) onlyWhenLocked(_wallet) { address locker = lockStorage.getLocker(_wallet); require(locker == address(this), "LM: cannot unlock a wallet that was locked by another feature"); setLock(_wallet, 0); emit Unlocked(_wallet); } /** * @notice Returns the release time of a wallet lock or 0 if the wallet is unlocked. * @param _wallet The target wallet. * @return _releaseAfter The epoch time at which the lock will release (in seconds). */ function getLock(address _wallet) external view returns(uint64 _releaseAfter) { uint256 lockEnd = lockStorage.getLock(_wallet); if (lockEnd > block.timestamp) { _releaseAfter = uint64(lockEnd); } } /** * @notice Checks if a wallet is locked. * @param _wallet The target wallet. * @return _isLocked `true` if the wallet is locked otherwise `false`. */ function isLocked(address _wallet) external view returns (bool _isLocked) { return lockStorage.isLocked(_wallet); } /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external view override returns (uint256, OwnerSignature) { return (1, OwnerSignature.Disallowed); } // *************** Internal Functions ********************* // function setLock(address _wallet, uint256 _releaseAfter) internal { versionManager.invokeStorage( _wallet, address(lockStorage), abi.encodeWithSelector(lockStorage.setLock.selector, _wallet, address(this), _releaseAfter) ); } }
0x608060405234801561001057600080fd5b50600436106100c95760003560e01c80636b9db4e611610081578063d89784fc1161005b578063d89784fc146102af578063ea2347e6146102d3578063f435f5a71461032b576100c9565b80636b9db4e6146102185780639be65a601461025b578063a287fdbd14610281576100c9565b80633b73d67f116100b25780633b73d67f1461011c5780633fd8b02f146101c45780634a4fbeec146101de576100c9565b806319ab453c146100ce5780632f6c493c146100f6575b600080fd5b6100f4600480360360208110156100e457600080fd5b50356001600160a01b0316610351565b005b6100f46004803603602081101561010c57600080fd5b50356001600160a01b0316610354565b61019c6004803603604081101561013257600080fd5b6001600160a01b03823516919081019060408101602082013564010000000081111561015d57600080fd5b82018360208201111561016f57600080fd5b8035906020019184600183028401116401000000008311171561019157600080fd5b509092509050610629565b604051808381526020018260038111156101b257fe5b81526020019250505060405180910390f35b6101cc610635565b60408051918252519081900360200190f35b610204600480360360208110156101f457600080fd5b50356001600160a01b031661063b565b604080519115158252519081900360200190f35b61023e6004803603602081101561022e57600080fd5b50356001600160a01b03166106bb565b6040805167ffffffffffffffff9092168252519081900360200190f35b6100f46004803603602081101561027157600080fd5b50356001600160a01b0316610765565b6102046004803603604081101561029757600080fd5b506001600160a01b03813581169160200135166108f9565b6102b761099e565b604080516001600160a01b039092168252519081900360200190f35b6102db6109ad565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156103175781810151838201526020016102ff565b505050509050019250505060405180910390f35b6100f46004803603602081101561034157600080fd5b50356001600160a01b03166109b2565b50565b6003546040805163353ba5cd60e21b81526001600160a01b03808516600483015233602483015291518493600093169163d4ee9734916044808301926020929190829003018186803b1580156103a957600080fd5b505afa1580156103bd573d6000803e3d6000fd5b505050506040513d60208110156103d357600080fd5b505190506103e182336108f9565b806103e95750805b61043a576040805162461bcd60e51b815260206004820152601f60248201527f4c4d3a206d75737420626520677561726469616e206f72206665617475726500604482015290519081900360640190fd5b60005460408051631293efbb60e21b81526001600160a01b038087166004830152915186939290921691634a4fbeec91602480820192602092909190829003018186803b15801561048a57600080fd5b505afa15801561049e573d6000803e3d6000fd5b505050506040513d60208110156104b457600080fd5b5051610507576040805162461bcd60e51b815260206004820152601960248201527f4c4d3a2077616c6c6574206d757374206265206c6f636b656400000000000000604482015290519081900360640190fd5b60008054604080517f919884bf0000000000000000000000000000000000000000000000000000000081526001600160a01b0388811660048301529151919092169163919884bf916024808301926020929190829003018186803b15801561056e57600080fd5b505afa158015610582573d6000803e3d6000fd5b505050506040513d602081101561059857600080fd5b505190506001600160a01b03811630146105e35760405162461bcd60e51b815260040180806020018281038252603d815260200180610d40603d913960400191505060405180910390fd5b6105ee856000610bc9565b6040516001600160a01b038616907f7e6adfec7e3f286831a0200a754127c171a2da564078722cb97704741bbdb0ea90600090a25050505050565b60016003935093915050565b60025481565b6000805460408051631293efbb60e21b81526001600160a01b03858116600483015291519190921691634a4fbeec916024808301926020929190829003018186803b15801561068957600080fd5b505afa15801561069d573d6000803e3d6000fd5b505050506040513d60208110156106b357600080fd5b505192915050565b60008054604080517f6b9db4e60000000000000000000000000000000000000000000000000000000081526001600160a01b038581166004830152915184939290921691636b9db4e691602480820192602092909190829003018186803b15801561072557600080fd5b505afa158015610739573d6000803e3d6000fd5b505050506040513d602081101561074f57600080fd5b505190504281111561075f578091505b50919050565b6000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b1580156107b457600080fd5b505afa1580156107c8573d6000803e3d6000fd5b505050506040513d60208110156107de57600080fd5b5051600154604080516001600160a01b039283166024820152604480820185905282518083039091018152606490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb00000000000000000000000000000000000000000000000000000000178152915181519495509286169390929182918083835b6020831061088b5780518252601f19909201916020918201910161086c565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146108ed576040519150601f19603f3d011682016040523d82523d6000602084013e6108f2565b606091505b5050505050565b600154604080517f5a51fd430000000000000000000000000000000000000000000000000000000081526001600160a01b038581166004830152848116602483015291516000939290921691635a51fd4391604480820192602092909190829003018186803b15801561096b57600080fd5b505afa15801561097f573d6000803e3d6000fd5b505050506040513d602081101561099557600080fd5b50519392505050565b6003546001600160a01b031681565b606090565b6003546040805163353ba5cd60e21b81526001600160a01b03808516600483015233602483015291518493600093169163d4ee9734916044808301926020929190829003018186803b158015610a0757600080fd5b505afa158015610a1b573d6000803e3d6000fd5b505050506040513d6020811015610a3157600080fd5b50519050610a3f82336108f9565b80610a475750805b610a98576040805162461bcd60e51b815260206004820152601f60248201527f4c4d3a206d75737420626520677561726469616e206f72206665617475726500604482015290519081900360640190fd5b60005460408051631293efbb60e21b81526001600160a01b038087166004830152915186939290921691634a4fbeec91602480820192602092909190829003018186803b158015610ae857600080fd5b505afa158015610afc573d6000803e3d6000fd5b505050506040513d6020811015610b1257600080fd5b505115610b66576040805162461bcd60e51b815260206004820152601160248201527f42463a2077616c6c6574206c6f636b6564000000000000000000000000000000604482015290519081900360640190fd5b610b74846002544201610bc9565b836001600160a01b03167f6395bace6e0acbe4f22761b149d3cc2e88c7dde6bf4d8481825eef404cf989a16002544201604051808267ffffffffffffffff16815260200191505060405180910390a250505050565b60015460008054604080516001600160a01b0387811660248084018290523060448086019190915260648086018b9052865180870382018152608496870188526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f6b221d140000000000000000000000000000000000000000000000000000000017815297517fe452b7900000000000000000000000000000000000000000000000000000000081526004810195865298861693890184905260609289019283528051918901919091528051949099169863e452b790988c98939791969495929493909301929091908190849084905b83811015610cd5578181015183820152602001610cbd565b50505050905090810190601f168015610d025780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b158015610d2357600080fd5b505af1158015610d37573d6000803e3d6000fd5b50505050505056fe4c4d3a2063616e6e6f7420756e6c6f636b20612077616c6c6574207468617420776173206c6f636b656420627920616e6f746865722066656174757265a2646970667358221220756a7c20930cc8ea3dcb33c47b8e39a5ded17ffebfe50caf5c0730bd189f0efd64736f6c634300060c0033
[ 8 ]
0x431e57cddd59a1b7b41dbfe478a03d52b796175f
pragma solidity 0.6.0; 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { 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) { 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; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract Meta is ERC20 { constructor(uint256 initialSupply) public ERC20("Meta", "META") { _mint(msg.sender, initialSupply); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063395093511161007157806339509351146101d957806370a082311461020557806395d89b411461022b578063a457c2d714610233578063a9059cbb1461025f578063dd62ed3e1461028b576100a9565b806306fdde03146100ae578063095ea7b31461012b57806318160ddd1461016b57806323b872dd14610185578063313ce567146101bb575b600080fd5b6100b66102b9565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f05781810151838201526020016100d8565b50505050905090810190601f16801561011d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101576004803603604081101561014157600080fd5b506001600160a01b03813516906020013561034f565b604080519115158252519081900360200190f35b61017361036c565b60408051918252519081900360200190f35b6101576004803603606081101561019b57600080fd5b506001600160a01b03813581169160208101359091169060400135610372565b6101c36103ff565b6040805160ff9092168252519081900360200190f35b610157600480360360408110156101ef57600080fd5b506001600160a01b038135169060200135610408565b6101736004803603602081101561021b57600080fd5b50356001600160a01b031661045c565b6100b6610477565b6101576004803603604081101561024957600080fd5b506001600160a01b0381351690602001356104d8565b6101576004803603604081101561027557600080fd5b506001600160a01b038135169060200135610546565b610173600480360360408110156102a157600080fd5b506001600160a01b038135811691602001351661055a565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b820191906000526020600020905b81548152906001019060200180831161032857829003601f168201915b5050505050905090565b600061036361035c610585565b8484610589565b50600192915050565b60025490565b600061037f848484610675565b6103f58461038b610585565b6103f085604051806060016040528060288152602001610945602891396001600160a01b038a166000908152600160205260408120906103c9610585565b6001600160a01b03168152602081019190915260400160002054919063ffffffff6107dc16565b610589565b5060019392505050565b60055460ff1690565b6000610363610415610585565b846103f08560016000610426610585565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff61087316565b6001600160a01b031660009081526020819052604090205490565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b60006103636104e5610585565b846103f0856040518060600160405280602581526020016109b6602591396001600061050f610585565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff6107dc16565b6000610363610553610585565b8484610675565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b3390565b6001600160a01b0383166105ce5760405162461bcd60e51b81526004018080602001828103825260248152602001806109926024913960400191505060405180910390fd5b6001600160a01b0382166106135760405162461bcd60e51b81526004018080602001828103825260228152602001806108fd6022913960400191505060405180910390fd5b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166106ba5760405162461bcd60e51b815260040180806020018281038252602581526020018061096d6025913960400191505060405180910390fd5b6001600160a01b0382166106ff5760405162461bcd60e51b81526004018080602001828103825260238152602001806108da6023913960400191505060405180910390fd5b61070a8383836108d4565b61074d8160405180606001604052806026815260200161091f602691396001600160a01b038616600090815260208190526040902054919063ffffffff6107dc16565b6001600160a01b038085166000908152602081905260408082209390935590841681522054610782908263ffffffff61087316565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b6000818484111561086b5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610830578181015183820152602001610818565b50505050905090810190601f16801561085d5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6000828201838110156108cd576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220c2a880ba2ef0b933903443826d0ea165ba500cb93986d67c1d9de5cc78ec2d0564736f6c63430006000033
[ 38 ]
0x43c494cB39Ef9DE842b71055edcD193030281F1b
pragma solidity 0.6.8; pragma experimental ABIEncoderV2; 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; } 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); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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) { // 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"); } } library Accountant { using SafeMath for uint256; uint public constant interestDecimals = 1e18; uint public constant blocksPerDay = 5760; uint public constant blocksPerYear = (blocksPerDay * 365); struct PaymentAllocation { uint interestPayment; uint principalPayment; uint additionalBalancePayment; } function calculateInterestAndPrincipalAccrued(CreditLine cl, uint blockNumber) public view returns(uint, uint) { uint totalPayment = calculateAnnuityPayment(cl.balance(), cl.interestApr(), cl.termInDays(), cl.paymentPeriodInDays()); uint interestAccrued = calculateInterestAccrued(cl, blockNumber); uint principalAccrued = calculatePrincipalAccrued(cl, totalPayment, interestAccrued, blockNumber); return (interestAccrued, principalAccrued); } function calculatePrincipalAccrued(CreditLine cl, uint periodPayment, uint interestAccrued, uint blockNumber) public view returns(uint) { uint blocksPerPaymentPeriod = blocksPerDay * cl.paymentPeriodInDays(); // Math.min guards against overflow. See comment in the calculateInterestAccrued for further explanation. uint lastUpdatedBlock = Math.min(blockNumber, cl.lastUpdatedBlock()); uint numBlocksElapsed = blockNumber.sub(lastUpdatedBlock); int128 fractionOfPeriod = FPMath.divi(int256(numBlocksElapsed), int256(blocksPerPaymentPeriod)); uint periodPaymentFraction = uint(FPMath.muli(fractionOfPeriod, int256(periodPayment))); return periodPaymentFraction.sub(interestAccrued); } function calculateInterestAccrued(CreditLine cl, uint blockNumber) public view returns(uint) { // We use Math.min here to prevent integer overflow (ie. go negative) when calculating // numBlocksElapsed. Typically this shouldn't be possible, because // the lastUpdatedBlock couldn't be *after* the current blockNumber. However, when assessing // we allow this function to be called with a past block number, which raises the possibility // of overflow. // This use of min should not generate incorrect interest calculations, since // this functions purpose is just to normalize balances, and will be called any time // a balance affecting action takes place (eg. drawdown, repayment, assessment) uint lastUpdatedBlock = Math.min(blockNumber, cl.lastUpdatedBlock()); uint numBlocksElapsed = blockNumber.sub(lastUpdatedBlock); uint totalInterestPerYear = (cl.balance().mul(cl.interestApr())).div(interestDecimals); return totalInterestPerYear.mul(numBlocksElapsed).div(blocksPerYear); } function calculateAnnuityPayment(uint balance, uint interestApr, uint termInDays, uint paymentPeriodInDays) public pure returns(uint) { /* This is the standard amortization formula for an annuity payment amount. See: https://en.wikipedia.org/wiki/Amortization_calculator The specific formula we're interested in can be expressed as: `balance * (periodRate / (1 - (1 / ((1 + periodRate) ^ periods_per_term))))` FPMath is a library designed for emulating floating point numbers in solidity. At a high level, we are just turning all our uint256 numbers into floating points and doing the formula above, and then turning it back into an int64 at the end. */ // Components used in the formula uint periodsPerTerm = termInDays / paymentPeriodInDays; int128 one = FPMath.fromInt(int256(1)); int128 annualRate = FPMath.divi(int256(interestApr), int256(interestDecimals)); int128 dailyRate = FPMath.div(annualRate, FPMath.fromInt(int256(365))); int128 periodRate = FPMath.mul(dailyRate, FPMath.fromInt(int256(paymentPeriodInDays))); int128 termRate = FPMath.pow(FPMath.add(one, periodRate), periodsPerTerm); int128 denominator = FPMath.sub(one, FPMath.div(one, termRate)); if (denominator == 0) { return balance / periodsPerTerm; } int128 paymentFractionFP = FPMath.div(periodRate, denominator); uint paymentFraction = uint(FPMath.muli(paymentFractionFP, int256(1e18))); return (balance * paymentFraction) / 1e18; } function allocatePayment(uint paymentAmount, uint balance, uint interestOwed, uint principalOwed) public pure returns(PaymentAllocation memory) { uint paymentRemaining = paymentAmount; uint interestPayment = Math.min(interestOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(interestPayment); uint principalPayment = Math.min(principalOwed, paymentRemaining); paymentRemaining = paymentRemaining.sub(principalPayment); uint balanceRemaining = balance.sub(principalPayment); uint additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining); return PaymentAllocation({ interestPayment: interestPayment, principalPayment: principalPayment, additionalBalancePayment: additionalBalancePayment }); } } ibrary FPMath { /** @dev * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /** @dev * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { return int64 (x >> 64); } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { require (x >= 0); return uint64 (x >> 64); } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { return int256 (x) << 64; } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (x) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return -x; } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { require (x != MIN_64x64); return x < 0 ? -x : x; } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { return int128 ((int256 (x) + int256 (y)) >> 1); } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1)); } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { uint256 absoluteResult; bool negativeResult = false; if (x >= 0) { absoluteResult = powu (uint256 (x) << 63, y); } else { // We rely on overflow behavior here absoluteResult = powu (uint256 (uint128 (-x)) << 63, y); negativeResult = y & 1 > 0; } absoluteResult >>= 63; if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { require (x >= 0); return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000)); } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (x) << 127 - msb; for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { require (x > 0); return int128 ( uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128); } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= 63 - (x >> 64); require (result <= uint256 (MAX_64x64)); return int128 (result); } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } /** * Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point * number and y is unsigned 256-bit integer number. Revert on overflow. * * @param x unsigned 129.127-bit fixed point number * @param y uint256 value * @return unsigned 129.127-bit fixed point number */ function powu (uint256 x, uint256 y) private pure returns (uint256) { if (y == 0) return 0x80000000000000000000000000000000; else if (x == 0) return 0; else { int256 msb = 0; uint256 xc = x; if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 xe = msb - 127; if (xe > 0) x >>= xe; else x <<= -xe; uint256 result = 0x80000000000000000000000000000000; int256 re = 0; while (y > 0) { if (y & 1 > 0) { result = result * x; y -= 1; re += xe; if (result >= 0x8000000000000000000000000000000000000000000000000000000000000000) { result >>= 128; re += 1; } else result >>= 127; if (re < -127) return 0; // Underflow require (re < 128); // Overflow } else { x = x * x; y >>= 1; xe <<= 1; if (x >= 0x8000000000000000000000000000000000000000000000000000000000000000) { x >>= 128; xe += 1; } else x >>= 127; if (xe < -127) return 0; // Underflow require (xe < 128); // Overflow } } if (re > 0) result <<= re; else if (re < 0) result >>= -re; return result; } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x, uint256 r) private pure returns (uint128) { if (x == 0) return 0; else { require (r > 0); while (true) { uint256 rr = x / r; if (r == rr || r + 1 == rr) return uint128 (r); else if (r == rr + 1) return uint128 (rr); r = r + rr + 1 >> 1; } } } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } contract ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } contract CreditLine is Initializable, OwnableUpgradeSafe { // Credit line terms address public borrower; address public underwriter; uint public collateral; uint public limit; uint public interestApr; uint public minCollateralPercent; uint public paymentPeriodInDays; uint public termInDays; // Accounting variables uint public balance; uint public interestOwed; uint public principalOwed; uint public prepaymentBalance; uint public collateralBalance; uint public termEndBlock; uint public nextDueBlock; uint public lastUpdatedBlock; function initialize( address _borrower, address _underwriter, uint _limit, uint _interestApr, uint _minCollateralPercent, uint _paymentPeriodInDays, uint _termInDays ) public initializer { __Ownable_init(); borrower = _borrower; underwriter = _underwriter; limit = _limit; interestApr = _interestApr; minCollateralPercent = _minCollateralPercent; paymentPeriodInDays = _paymentPeriodInDays; termInDays = _termInDays; lastUpdatedBlock = block.number; } function setTermEndBlock(uint newTermEndBlock) external onlyOwner returns (uint) { return termEndBlock = newTermEndBlock; } function setNextDueBlock(uint newNextDueBlock) external onlyOwner returns (uint) { return nextDueBlock = newNextDueBlock; } function setBalance(uint newBalance) external onlyOwner returns(uint) { return balance = newBalance; } function setInterestOwed(uint newInterestOwed) external onlyOwner returns (uint) { return interestOwed = newInterestOwed; } function setPrincipalOwed(uint newPrincipalOwed) external onlyOwner returns (uint) { return principalOwed = newPrincipalOwed; } function setPrepaymentBalance(uint newPrepaymentBalance) external onlyOwner returns (uint) { return prepaymentBalance = newPrepaymentBalance; } function setCollateralBalance(uint newCollateralBalance) external onlyOwner returns (uint) { return collateralBalance = newCollateralBalance; } function setLastUpdatedBlock(uint newLastUpdatedBlock) external onlyOwner returns (uint) { return lastUpdatedBlock = newLastUpdatedBlock; } function setLimit(uint newAmount) external onlyOwnerOrUnderwriter returns (uint) { return limit = newAmount; } function authorizePool(address poolAddress) external onlyOwner { address erc20address = Pool(poolAddress).erc20address(); // Approve the pool for an infinite amount ERC20UpgradeSafe(erc20address).approve(poolAddress, uint(-1)); } modifier onlyOwnerOrUnderwriter() { require((msg.sender == owner() || msg.sender == underwriter), "Restricted to owner or underwriter"); _; } } contract OwnerPausable is OwnableUpgradeSafe, PausableUpgradeSafe { function __OwnerPausable__init() public { __Pausable_init_unchained(); } /** * @dev Pauses all functions guarded by Pause * * See {Pausable-_pause}. * * Requirements: * * - the caller must be the owner. */ function pause() public onlyOwner { _pause(); } /** * @dev Unpauses the contract * * See {Pausable-_unpause}. * * Requirements: * * - the caller must be the owner`. */ function unpause() public onlyOwner { _unpause(); } } contract Pool is Initializable, OwnableUpgradeSafe, OwnerPausable { using SafeMath for uint256; uint public sharePrice; uint mantissa; uint public totalShares; mapping(address => uint) public capitalProviders; address public erc20address; string name; uint public totalFundsLimit = 0; uint public transactionLimit = 0; event DepositMade(address indexed capitalProvider, uint amount); event WithdrawalMade(address indexed capitalProvider, uint amount); event TransferMade(address indexed from, address indexed to, uint amount); event InterestCollected(address indexed payer, uint amount); event PrincipalCollected(address indexed payer, uint amount); event LimitChanged(address indexed owner, string limitType, uint amount); function initialize(address _erc20address, string memory _name, uint _mantissa) public initializer { __Context_init_unchained(); __Ownable_init_unchained(); __OwnerPausable__init(); name = _name; erc20address = _erc20address; mantissa = _mantissa; sharePrice = _mantissa; // Sanity check the address ERC20UpgradeSafe(erc20address).totalSupply(); // Unlock self for infinite amount ERC20UpgradeSafe(erc20address).approve(address(this), uint(-1)); } function deposit(uint amount) external payable whenNotPaused { require(transactionWithinLimit(amount), "Amount is over the per-transaction limit."); // Determine current shares the address has, and the amount of new shares to be added uint currentShares = capitalProviders[msg.sender]; uint depositShares = getNumShares(amount, mantissa, sharePrice); uint potentialNewTotalShares = totalShares.add(depositShares); require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit."); doERC20Transfer(msg.sender, address(this), amount); // Add the new shares to both the pool and the address totalShares = totalShares.add(depositShares); capitalProviders[msg.sender] = currentShares.add(depositShares); emit DepositMade(msg.sender, amount); } function withdraw(uint amount) external whenNotPaused { // Determine current shares the address has and the shares requested to withdraw require(transactionWithinLimit(amount), "Amount is over the per-transaction limit"); uint currentShares = capitalProviders[msg.sender]; uint withdrawShares = getNumShares(amount, mantissa, sharePrice); // Ensure the address has enough value in the pool require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns"); // Remove the new shares from both the pool and the address totalShares = totalShares.sub(withdrawShares); capitalProviders[msg.sender] = currentShares.sub(withdrawShares); // Send the amount to the address doERC20Transfer(address(this), msg.sender, amount); emit WithdrawalMade(msg.sender, amount); } function collectInterestRepayment(address from, uint amount) external whenNotPaused { doERC20Transfer(from, address(this), amount); uint increment = amount.mul(mantissa).div(totalShares); sharePrice = sharePrice + increment; emit InterestCollected(from, amount); } function collectPrincipalRepayment(address from, uint amount) external whenNotPaused { // Purposefully does nothing except receive money. No share price updates for principal. doERC20Transfer(from, address(this), amount); emit PrincipalCollected(from, amount); } function setTotalFundsLimit(uint amount) public onlyOwner whenNotPaused { totalFundsLimit = amount; emit LimitChanged(msg.sender, "totalFundsLimit", amount); } function setTransactionLimit(uint amount) public onlyOwner whenNotPaused { transactionLimit = amount; emit LimitChanged(msg.sender, "transactionLimit", amount); } function transferFrom(address from, address to, uint amount) public onlyOwner whenNotPaused returns (bool) { bool result = doERC20Transfer(from, to, amount); emit TransferMade(from, to, amount); return result; } function enoughBalance(address user, uint amount) public view whenNotPaused returns(bool) { return ERC20UpgradeSafe(erc20address).balanceOf(user) >= amount; } /* Internal Functions */ function poolWithinLimit(uint _totalShares) internal view returns (bool) { return _totalShares.mul(sharePrice).div(mantissa) <= totalFundsLimit; } function transactionWithinLimit(uint amount) internal view returns (bool) { return amount <= transactionLimit; } function getNumShares(uint amount, uint multiplier, uint price) internal pure returns (uint) { return amount.mul(multiplier).div(price); } function doERC20Transfer(address from, address to, uint amount) internal returns (bool) { ERC20UpgradeSafe erc20 = ERC20UpgradeSafe(erc20address); uint balanceBefore = erc20.balanceOf(to); bool success = erc20.transferFrom(from, to, amount); // Calculate the amount that was *actually* transferred uint balanceAfter = erc20.balanceOf(to); require(balanceAfter >= balanceBefore, "Token Transfer Overflow Error"); return success; } function doERC20Withdraw(address payable to, uint amount) internal returns (bool) { ERC20UpgradeSafe erc20 = ERC20UpgradeSafe(erc20address); bool success = erc20.transfer(to, amount); require(success, "Token Withdraw Failed"); return success; } } contract FakeV2CreditDesk is Initializable, OwnableUpgradeSafe, OwnerPausable { using SafeMath for uint256; // Approximate number of blocks uint public constant blocksPerDay = 5760; address public poolAddress; uint public maxUnderwriterLimit = 0; uint public transactionLimit = 0; struct Underwriter { uint governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentMade(address indexed payer, address indexed creditLine, uint interestAmount, uint principalAmount, uint remainingAmount); event PrepaymentMade(address indexed payer, address indexed creditLine, uint prepaymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint newLimit); event LimitChanged(address indexed owner, string limitType, uint amount); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; function initialize(address _poolAddress) public initializer { __Ownable_init(); poolAddress = _poolAddress; } function someBrandNewFunction() public pure returns(uint) { return 5; } function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } /* * Internal Functions */ } contract TestERC20 is ERC20UpgradeSafe { constructor(uint256 initialSupply, uint8 decimals) public { __ERC20_init("USDC", "USDC"); _setupDecimals(decimals); _mint(msg.sender, initialSupply); } } contract TestPool is Pool { function _getNumShares(uint amount, uint multiplier, uint price) public pure returns (uint) { return getNumShares(amount, multiplier, price); } } contract CreditDesk is Initializable, OwnableUpgradeSafe, OwnerPausable { using SafeMath for uint256; // Approximate number of blocks uint public constant blocksPerDay = 5760; address public poolAddress; uint public maxUnderwriterLimit = 0; uint public transactionLimit = 0; struct Underwriter { uint governanceLimit; address[] creditLines; } struct Borrower { address[] creditLines; } event PaymentMade(address indexed payer, address indexed creditLine, uint interestAmount, uint principalAmount, uint remainingAmount); event PrepaymentMade(address indexed payer, address indexed creditLine, uint prepaymentAmount); event DrawdownMade(address indexed borrower, address indexed creditLine, uint drawdownAmount); event CreditLineCreated(address indexed borrower, address indexed creditLine); event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress); event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint newLimit); event LimitChanged(address indexed owner, string limitType, uint amount); mapping(address => Underwriter) public underwriters; mapping(address => Borrower) private borrowers; function initialize(address _poolAddress) public initializer { __Ownable_init(); __OwnerPausable__init(); setPoolAddress(_poolAddress); } function setUnderwriterGovernanceLimit(address underwriterAddress, uint limit) external onlyOwner whenNotPaused { Underwriter storage underwriter = underwriters[underwriterAddress]; require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol"); underwriter.governanceLimit = limit; emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit); } function createCreditLine( address _borrower, uint _limit, uint _interestApr, uint _minCollateralPercent, uint _paymentPeriodInDays, uint _termInDays ) external whenNotPaused { Underwriter storage underwriter = underwriters[msg.sender]; Borrower storage borrower = borrowers[_borrower]; require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line"); CreditLine cl = new CreditLine(); cl.initialize(_borrower, msg.sender, _limit, _interestApr, _minCollateralPercent, _paymentPeriodInDays, _termInDays); cl.authorizePool(poolAddress); underwriter.creditLines.push(address(cl)); borrower.creditLines.push(address(cl)); emit CreditLineCreated(_borrower, address(cl)); } function drawdown(uint amount, address creditLineAddress) external whenNotPaused { CreditLine cl = CreditLine(creditLineAddress); require(cl.borrower() == msg.sender, "You do not belong to this credit line"); // Not strictly necessary, but provides a better error message to the user require(getPool().enoughBalance(poolAddress, amount), "Pool does not have enough balance for this drawdown"); require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); require(withinCreditLimit(amount, cl), "The borrower does not have enough credit limit for this drawdown"); if (cl.balance() == 0) { cl.setTermEndBlock(calculateNewTermEndBlock(cl)); cl.setNextDueBlock(calculateNextDueBlock(cl)); } (uint interestOwed, uint principalOwed) = getInterestAndPrincipalOwedAsOf(cl, block.number); uint balance = cl.balance().add(amount); updateCreditLineAccounting(cl, balance, interestOwed, principalOwed); getPool().transferFrom(poolAddress, msg.sender, amount); emit DrawdownMade(msg.sender, address(cl), amount); } function pay(address creditLineAddress, uint amount) external payable whenNotPaused { CreditLine cl = CreditLine(creditLineAddress); require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); // Not strictly necessary, but provides a faster/better error message to the user require(getPool().enoughBalance(msg.sender, amount), "You have insufficent balance for this payment"); (uint paymentRemaining, uint interestPayment, uint principalPayment) = handlePayment(cl, amount, block.number, true); if (paymentRemaining > 0) { getPool().transferFrom(msg.sender, creditLineAddress, paymentRemaining); cl.setCollateralBalance(cl.collateralBalance().add(paymentRemaining)); } if (interestPayment > 0) { getPool().collectInterestRepayment(msg.sender, interestPayment); } if (principalPayment > 0) { getPool().collectPrincipalRepayment(msg.sender, principalPayment); } emit PaymentMade(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); } function prepay(address payable creditLineAddress, uint amount) external payable whenNotPaused { CreditLine cl = CreditLine(creditLineAddress); require(withinTransactionLimit(amount), "Amount is over the per-transaction limit"); getPool().transferFrom(msg.sender, creditLineAddress, amount); uint newPrepaymentBalance = cl.prepaymentBalance().add(amount); cl.setPrepaymentBalance(newPrepaymentBalance); emit PrepaymentMade(msg.sender, address(cl), amount); } function addCollateral(address payable creditLineAddress, uint amount) external payable whenNotPaused { CreditLine cl = CreditLine(creditLineAddress); getPool().transferFrom(msg.sender, creditLineAddress, amount); uint newCollateralBalance = cl.collateralBalance().add(amount); cl.setCollateralBalance(newCollateralBalance); } function assessCreditLine(address creditLineAddress) external whenNotPaused { CreditLine cl = CreditLine(creditLineAddress); // Do not assess until a full period has elapsed if (block.number < cl.nextDueBlock()) { return; } (uint paymentRemaining, uint interestPayment, uint principalPayment) = handlePayment(cl, cl.prepaymentBalance(), cl.nextDueBlock(), false); cl.setPrepaymentBalance(paymentRemaining); getPool().collectInterestRepayment(msg.sender, interestPayment); getPool().collectPrincipalRepayment(msg.sender, principalPayment); cl.setNextDueBlock(calculateNextDueBlock(cl)); if (cl.principalOwed() > 0) { handleLatePayments(cl); } emit PaymentMade(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining); } function setPoolAddress(address newPoolAddress) public onlyOwner whenNotPaused returns (address) { // Sanity check the new address; Pool(newPoolAddress).totalShares(); emit PoolAddressUpdated(poolAddress, newPoolAddress); return poolAddress = newPoolAddress; } function setMaxUnderwriterLimit(uint amount) public onlyOwner whenNotPaused { maxUnderwriterLimit = amount; emit LimitChanged(msg.sender, "maxUnderwriterLimit", amount); } function setTransactionLimit(uint amount) public onlyOwner whenNotPaused { transactionLimit = amount; emit LimitChanged(msg.sender, "transactionLimit", amount); } // Public View Functions (Getters) function getUnderwriterCreditLines(address underwriterAddress) public view whenNotPaused returns (address[] memory) { return underwriters[underwriterAddress].creditLines; } function getBorrowerCreditLines(address borrowerAddress) public view whenNotPaused returns (address[] memory) { return borrowers[borrowerAddress].creditLines; } /* * Internal Functions */ function handlePayment(CreditLine cl, uint paymentAmount, uint asOfBlock, bool allowFullBalancePayOff) internal returns (uint, uint, uint) { (uint interestOwed, uint principalOwed) = getInterestAndPrincipalOwedAsOf(cl, asOfBlock); Accountant.PaymentAllocation memory pa = Accountant.allocatePayment(paymentAmount, cl.balance(), interestOwed, principalOwed); uint newBalance = cl.balance().sub(pa.principalPayment); if (allowFullBalancePayOff) { newBalance = newBalance.sub(pa.additionalBalancePayment); } uint totalPrincipalPayment = cl.balance().sub(newBalance); uint paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment); updateCreditLineAccounting(cl, newBalance, interestOwed.sub(pa.interestPayment), principalOwed.sub(pa.principalPayment)); assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount); return (paymentRemaining, pa.interestPayment, totalPrincipalPayment); } function handleLatePayments(CreditLine cl) internal { // No op for now; } function getPool() internal view returns (Pool) { return Pool(poolAddress); } function getInterestAndPrincipalOwedAsOf(CreditLine cl, uint blockNumber) internal view returns (uint, uint) { (uint interestAccrued, uint principalAccrued) = Accountant.calculateInterestAndPrincipalAccrued(cl, blockNumber); return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued)); } function withinCreditLimit(uint amount, CreditLine cl) internal view returns(bool) { return cl.balance().add(amount) <= cl.limit(); } function withinTransactionLimit(uint amount) internal view returns(bool) { return amount <= transactionLimit; } function calculateNewTermEndBlock(CreditLine cl) internal view returns (uint) { return block.number.add(blocksPerDay.mul(cl.termInDays())); } function calculateNextDueBlock(CreditLine cl) internal view returns (uint) { uint blocksPerPeriod = cl.paymentPeriodInDays().mul(blocksPerDay); uint currentNextDueBlock; if (cl.nextDueBlock() != 0) { currentNextDueBlock = cl.nextDueBlock(); } else { currentNextDueBlock = block.number; } return currentNextDueBlock.add(blocksPerPeriod); } function underwriterCanCreateThisCreditLine(uint newAmount, Underwriter storage underwriter) internal view returns(bool) { uint creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter); uint totalToBeExtended = creditCurrentlyExtended.add(newAmount); return totalToBeExtended <= underwriter.governanceLimit; } function withinMaxUnderwriterLimit(uint amount) internal view returns (bool) { return amount <= maxUnderwriterLimit; } function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint) { uint creditExtended = 0; for (uint i = 0; i < underwriter.creditLines.length; i++) { CreditLine cl = CreditLine(underwriter.creditLines[i]); creditExtended = creditExtended.add(cl.limit()); } return creditExtended; } function updateCreditLineAccounting(CreditLine cl, uint balance, uint interestOwed, uint principalOwed) internal { cl.setBalance(balance); cl.setInterestOwed(interestOwed); cl.setPrincipalOwed(principalOwed); cl.setLastUpdatedBlock(block.number); if (balance == 0) { cl.setTermEndBlock(0); cl.setNextDueBlock(0); } } }
0x6080604052600436106101665760003560e01c80637d533642116100d1578063c4d66de81161008a578063f19605d611610064578063f19605d6146103cd578063f2fde38b146103e2578063f3b7d81514610402578063f5c7e0e21461041557610166565b8063c4d66de814610378578063e9e15b4f14610398578063f0c30cac146103b857610166565b80637d533642146102ce578063844a28c3146102ee5780638456cb591461031b5780638da5cb5b14610330578063c26ff93614610345578063c40768761461036557610166565b80635c080853116101235780635c0808531461022f5780635c975abb1461024f57806364bfa546146102715780636d75b9ee14610291578063715018a6146102a45780637216e7c8146102b957610166565b80630e4645ef1461016b5780631755ff211461018d578063200d3d49146101b85780633f4ba83a146101d8578063440c41bb146101ed5780634cfea68a1461020d575b600080fd5b34801561017757600080fd5b5061018b610186366004612d03565b610435565b005b34801561019957600080fd5b506101a261051e565b6040516101af9190612e59565b60405180910390f35b3480156101c457600080fd5b5061018b6101d3366004612dd7565b61052d565b3480156101e457600080fd5b5061018b6105c7565b3480156101f957600080fd5b5061018b610208366004612e07565b610606565b34801561021957600080fd5b50610222610aca565b6040516101af9190612f40565b34801561023b57600080fd5b5061018b61024a366004612d15565b610ad0565b34801561025b57600080fd5b50610264610cc1565b6040516101af9190612f35565b34801561027d57600080fd5b5061018b61028c366004612dd7565b610cca565b61018b61029f366004612cd8565b610d59565b3480156102b057600080fd5b5061018b610ece565b3480156102c557600080fd5b50610222610f4d565b3480156102da57600080fd5b506102226102e9366004612ca0565b610f53565b3480156102fa57600080fd5b5061030e610309366004612ca0565b610f65565b6040516101af9190612ee8565b34801561032757600080fd5b5061018b611002565b34801561033c57600080fd5b506101a261103f565b34801561035157600080fd5b5061030e610360366004612ca0565b61104e565b61018b610373366004612d03565b6110e6565b34801561038457600080fd5b5061018b610393366004612ca0565b6114c8565b3480156103a457600080fd5b506101a26103b3366004612ca0565b611566565b3480156103c457600080fd5b5061018b61168b565b3480156103d957600080fd5b50610222611693565b3480156103ee57600080fd5b5061018b6103fd366004612ca0565b611699565b61018b610410366004612cd8565b611750565b34801561042157600080fd5b5061018b610430366004612ca0565b611935565b61043d611df0565b6065546001600160a01b039081169116146104735760405162461bcd60e51b815260040161046a9061325f565b60405180910390fd5b60975460ff16156104965760405162461bcd60e51b815260040161046a90613114565b6001600160a01b038216600090815260cc602052604090206104b782611df4565b6104d35760405162461bcd60e51b815260040161046a906132e2565b8181556040516001600160a01b038416907f7be5403eca163f383a39c2d1f65a8fee2c9e41e7e6b150f4abfe16eaaf1d907690610511908590612f40565b60405180910390a2505050565b60c9546001600160a01b031681565b610535611df0565b6065546001600160a01b039081169116146105625760405162461bcd60e51b815260040161046a9061325f565b60975460ff16156105855760405162461bcd60e51b815260040161046a90613114565b60ca81905560405133907fd051fbd9d5bbce3751e47a2ff88ee7dde1a0c474fad43693046c1f6237841dc8906105bc90849061333f565b60405180910390a250565b6105cf611df0565b6065546001600160a01b039081169116146105fc5760405162461bcd60e51b815260040161046a9061325f565b610604611dfc565b565b60975460ff16156106295760405162461bcd60e51b815260040161046a90613114565b6000819050336001600160a01b0316816001600160a01b0316637df1f1b96040518163ffffffff1660e01b815260040160206040518083038186803b15801561067157600080fd5b505afa158015610685573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106a99190612cbc565b6001600160a01b0316146106cf5760405162461bcd60e51b815260040161046a90613186565b6106d7611e68565b60c95460405163c34e584160e01b81526001600160a01b039283169263c34e58419261070a929116908790600401612e91565b60206040518083038186803b15801561072257600080fd5b505afa158015610736573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061075a9190612d60565b6107765760405162461bcd60e51b815260040161046a906131cb565b61077f83611e77565b61079b5760405162461bcd60e51b815260040161046a9061313e565b6107a58382611e7f565b6107c15760405162461bcd60e51b815260040161046a90613374565b806001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b1580156107fa57600080fd5b505afa15801561080e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108329190612def565b61094557806001600160a01b031663fb9eb99061084e83611f3a565b6040518263ffffffff1660e01b815260040161086a9190612f40565b602060405180830381600087803b15801561088457600080fd5b505af1158015610898573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108bc9190612def565b50806001600160a01b0316637957dda36108d583611fcf565b6040518263ffffffff1660e01b81526004016108f19190612f40565b602060405180830381600087803b15801561090b57600080fd5b505af115801561091f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109439190612def565b505b6000806109528343612162565b9150915060006109d986856001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b505afa1580156109a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109cd9190612def565b9063ffffffff61227b16565b90506109e7848285856122a7565b6109ef611e68565b60c9546040516323b872dd60e01b81526001600160a01b03928316926323b872dd92610a249291169033908b90600401612e6d565b602060405180830381600087803b158015610a3e57600080fd5b505af1158015610a52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a769190612d60565b50836001600160a01b0316336001600160a01b03167f7ec4669c579321a5cf5a6b525637eb0924a93e2e11eab9d14be8b44de1116b1b88604051610aba9190612f40565b60405180910390a3505050505050565b61168081565b60975460ff1615610af35760405162461bcd60e51b815260040161046a90613114565b33600090815260cc602090815260408083206001600160a01b038a16845260cd909252909120610b23878361255b565b610b3f5760405162461bcd60e51b815260040161046a90613094565b6000604051610b4d90612c72565b604051809103906000f080158015610b69573d6000803e3d6000fd5b506040516376dfa56160e11b81529091506001600160a01b0382169063edbf4ac290610ba5908c9033908d908d908d908d908d90600401612eaa565b600060405180830381600087803b158015610bbf57600080fd5b505af1158015610bd3573d6000803e3d6000fd5b505060c95460405163182cdbe360e11b81526001600160a01b038086169450633059b7c69350610c07921690600401612e59565b600060405180830381600087803b158015610c2157600080fd5b505af1158015610c35573d6000803e3d6000fd5b5050506001808501805480830182556000918252602080832090910180546001600160a01b038088166001600160a01b0319928316811790935588549586018955888552928420909401805490941681179093556040519293508c16917fc1d7685016f2246662e70fe17df916e959813e9ab93d50c4f039c0c069c5f3719190a3505050505050505050565b60975460ff1690565b610cd2611df0565b6065546001600160a01b03908116911614610cff5760405162461bcd60e51b815260040161046a9061325f565b60975460ff1615610d225760405162461bcd60e51b815260040161046a90613114565b60cb81905560405133907fd051fbd9d5bbce3751e47a2ff88ee7dde1a0c474fad43693046c1f6237841dc8906105bc9084906130e2565b60975460ff1615610d7c5760405162461bcd60e51b815260040161046a90613114565b81610d85611e68565b6001600160a01b03166323b872dd3385856040518463ffffffff1660e01b8152600401610db493929190612e6d565b602060405180830381600087803b158015610dce57600080fd5b505af1158015610de2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e069190612d60565b506000610e4683836001600160a01b031663c98c05b76040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b6040516361cfbca160e01b81529091506001600160a01b038316906361cfbca190610e75908490600401612f40565b602060405180830381600087803b158015610e8f57600080fd5b505af1158015610ea3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ec79190612def565b5050505050565b610ed6611df0565b6065546001600160a01b03908116911614610f035760405162461bcd60e51b815260040161046a9061325f565b6065546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3606580546001600160a01b0319169055565b60ca5481565b60cc6020526000908152604090205481565b60975460609060ff1615610f8b5760405162461bcd60e51b815260040161046a90613114565b6001600160a01b038216600090815260cc602090815260409182902060010180548351818402810184019094528084529091830182828015610ff657602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610fd8575b50505050509050919050565b61100a611df0565b6065546001600160a01b039081169116146110375760405162461bcd60e51b815260040161046a9061325f565b610604612589565b6065546001600160a01b031690565b60975460609060ff16156110745760405162461bcd60e51b815260040161046a90613114565b6001600160a01b038216600090815260cd602090815260409182902080548351818402810184019094528084529091830182828015610ff6576020028201919060005260206000209081546001600160a01b03168152600190910190602001808311610fd85750505050509050919050565b60975460ff16156111095760405162461bcd60e51b815260040161046a90613114565b8161111382611e77565b61112f5760405162461bcd60e51b815260040161046a9061313e565b611137611e68565b6001600160a01b031663c34e584133846040518363ffffffff1660e01b8152600401611164929190612e91565b60206040518083038186803b15801561117c57600080fd5b505afa158015611190573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111b49190612d60565b6111d05760405162461bcd60e51b815260040161046a90613010565b60008060006111e284864360016125e2565b919450925090508215611335576111f7611e68565b6001600160a01b03166323b872dd3388866040518463ffffffff1660e01b815260040161122693929190612e6d565b602060405180830381600087803b15801561124057600080fd5b505af1158015611254573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112789190612d60565b50836001600160a01b03166361cfbca16112c585876001600160a01b031663c98c05b76040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b6040518263ffffffff1660e01b81526004016112e19190612f40565b602060405180830381600087803b1580156112fb57600080fd5b505af115801561130f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113339190612def565b505b81156113a357611343611e68565b6001600160a01b03166364de8a0733846040518363ffffffff1660e01b8152600401611370929190612e91565b600060405180830381600087803b15801561138a57600080fd5b505af115801561139e573d6000803e3d6000fd5b505050505b8015611411576113b1611e68565b6001600160a01b031663bcfa41ba33836040518363ffffffff1660e01b81526004016113de929190612e91565b600060405180830381600087803b1580156113f857600080fd5b505af115801561140c573d6000803e3d6000fd5b505050505b836001600160a01b0316846001600160a01b0316637df1f1b96040518163ffffffff1660e01b815260040160206040518083038186803b15801561145457600080fd5b505afa158015611468573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148c9190612cbc565b6001600160a01b03167f73bc067f8d6bb15a01636f9b76c6daa98472621717a0788af90498d8bfe69eb0848487604051610aba939291906133d2565b600054610100900460ff16806114e157506114e1612876565b806114ef575060005460ff16155b61150b5760405162461bcd60e51b815260040161046a90613294565b600054610100900460ff16158015611536576000805460ff1961ff0019909116610100171660011790555b61153e61287c565b61154661168b565b61154f82611566565b508015611562576000805461ff00191690555b5050565b6000611570611df0565b6065546001600160a01b0390811691161461159d5760405162461bcd60e51b815260040161046a9061325f565b60975460ff16156115c05760405162461bcd60e51b815260040161046a90613114565b816001600160a01b0316633a98ef396040518163ffffffff1660e01b815260040160206040518083038186803b1580156115f957600080fd5b505afa15801561160d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116319190612def565b5060c9546040516001600160a01b038085169216907fbc265b118422e9d29f4173594a64a9c2ac4d07373e209a941f4bc8c83c38321b90600090a35060c980546001600160a01b0319166001600160a01b03831617905590565b61060461290e565b60cb5481565b6116a1611df0565b6065546001600160a01b039081169116146116ce5760405162461bcd60e51b815260040161046a9061325f565b6001600160a01b0381166116f45760405162461bcd60e51b815260040161046a90612fca565b6065546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3606580546001600160a01b0319166001600160a01b0392909216919091179055565b60975460ff16156117735760405162461bcd60e51b815260040161046a90613114565b8161177d82611e77565b6117995760405162461bcd60e51b815260040161046a9061313e565b6117a1611e68565b6001600160a01b03166323b872dd3385856040518463ffffffff1660e01b81526004016117d093929190612e6d565b602060405180830381600087803b1580156117ea57600080fd5b505af11580156117fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118229190612d60565b50600061186283836001600160a01b031663ca3152e56040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b6040516320f8d09360e11b81529091506001600160a01b038316906341f1a12690611891908490600401612f40565b602060405180830381600087803b1580156118ab57600080fd5b505af11580156118bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118e39190612def565b50816001600160a01b0316336001600160a01b03167f83846cba5d937a7cd93b3dbb931c1cd260ce7a8ba928f072848719da0666e741856040516119279190612f40565b60405180910390a350505050565b60975460ff16156119585760405162461bcd60e51b815260040161046a90613114565b6000819050806001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561199657600080fd5b505afa1580156119aa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119ce9190612def565b4310156119db5750611ded565b6000806000611acd84856001600160a01b031663ca3152e56040518163ffffffff1660e01b815260040160206040518083038186803b158015611a1d57600080fd5b505afa158015611a31573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a559190612def565b866001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b158015611a8e57600080fd5b505afa158015611aa2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ac69190612def565b60006125e2565b925092509250836001600160a01b03166341f1a126846040518263ffffffff1660e01b8152600401611aff9190612f40565b602060405180830381600087803b158015611b1957600080fd5b505af1158015611b2d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b519190612def565b50611b5a611e68565b6001600160a01b03166364de8a0733846040518363ffffffff1660e01b8152600401611b87929190612e91565b600060405180830381600087803b158015611ba157600080fd5b505af1158015611bb5573d6000803e3d6000fd5b50505050611bc1611e68565b6001600160a01b031663bcfa41ba33836040518363ffffffff1660e01b8152600401611bee929190612e91565b600060405180830381600087803b158015611c0857600080fd5b505af1158015611c1c573d6000803e3d6000fd5b50505050836001600160a01b0316637957dda3611c3886611fcf565b6040518263ffffffff1660e01b8152600401611c549190612f40565b602060405180830381600087803b158015611c6e57600080fd5b505af1158015611c82573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ca69190612def565b506000846001600160a01b031663193501146040518163ffffffff1660e01b815260040160206040518083038186803b158015611ce257600080fd5b505afa158015611cf6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d1a9190612def565b1115611d2957611d2984611ded565b836001600160a01b0316846001600160a01b0316637df1f1b96040518163ffffffff1660e01b815260040160206040518083038186803b158015611d6c57600080fd5b505afa158015611d80573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da49190612cbc565b6001600160a01b03167f73bc067f8d6bb15a01636f9b76c6daa98472621717a0788af90498d8bfe69eb0848487604051611de0939291906133d2565b60405180910390a3505050505b50565b3390565b60ca54101590565b60975460ff16611e1e5760405162461bcd60e51b815260040161046a90612f9c565b6097805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611e51611df0565b604051611e5e9190612e59565b60405180910390a1565b60c9546001600160a01b031690565b60cb54101590565b6000816001600160a01b031663a4d66daf6040518163ffffffff1660e01b815260040160206040518083038186803b158015611eba57600080fd5b505afa158015611ece573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ef29190612def565b611f2f84846001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b111590505b92915050565b6000611f34611fc2836001600160a01b03166348e6f2966040518163ffffffff1660e01b815260040160206040518083038186803b158015611f7b57600080fd5b505afa158015611f8f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fb39190612def565b6116809063ffffffff61299a16565b439063ffffffff61227b16565b600080612055611680846001600160a01b03166399dd8df36040518163ffffffff1660e01b815260040160206040518083038186803b15801561201157600080fd5b505afa158015612025573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120499190612def565b9063ffffffff61299a16565b90506000836001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561209257600080fd5b505afa1580156120a6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120ca9190612def565b1561214757836001600160a01b031663500b245e6040518163ffffffff1660e01b815260040160206040518083038186803b15801561210857600080fd5b505afa15801561211c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121409190612def565b905061214a565b50435b61215a818363ffffffff61227b16565b949350505050565b60008060008073aebdbbec6a0a44dae994cd82675eb26acec19df9634678497187876040518363ffffffff1660e01b81526004016121a1929190612e91565b604080518083038186803b1580156121b857600080fd5b505af41580156121cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121f09190612e36565b9150915061223182876001600160a01b03166321856b366040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b61226e82886001600160a01b031663193501146040518163ffffffff1660e01b815260040160206040518083038186803b15801561099557600080fd5b9350935050509250929050565b6000828201838110156122a05760405162461bcd60e51b815260040161046a9061305d565b9392505050565b604051637d8b34e560e11b81526001600160a01b0385169063fb1669ca906122d3908690600401612f40565b602060405180830381600087803b1580156122ed57600080fd5b505af1158015612301573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123259190612def565b506040516396c8df3760e01b81526001600160a01b038516906396c8df3790612352908590600401612f40565b602060405180830381600087803b15801561236c57600080fd5b505af1158015612380573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123a49190612def565b5060405163b3b8a9c760e01b81526001600160a01b0385169063b3b8a9c7906123d1908490600401612f40565b602060405180830381600087803b1580156123eb57600080fd5b505af11580156123ff573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124239190612def565b506040516327e7b26360e01b81526001600160a01b038516906327e7b26390612450904390600401612f40565b602060405180830381600087803b15801561246a57600080fd5b505af115801561247e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124a29190612def565b508261255557604051630fb9eb9960e41b81526001600160a01b0385169063fb9eb990906124d590600090600401612f40565b602060405180830381600087803b1580156124ef57600080fd5b505af1158015612503573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125279190612def565b50604051637957dda360e01b81526001600160a01b03851690637957dda390610e7590600090600401612f40565b50505050565b600080612567836129d4565b9050600061257b828663ffffffff61227b16565b845410159250505092915050565b60975460ff16156125ac5760405162461bcd60e51b815260040161046a90613114565b6097805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611e51611df0565b60008060008060006125f48988612162565b91509150612600612c7f565b73aebdbbec6a0a44dae994cd82675eb26acec19df963d7cc2a038a8c6001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561265457600080fd5b505afa158015612668573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061268c9190612def565b86866040518563ffffffff1660e01b81526004016126ad94939291906133e8565b60606040518083038186803b1580156126c557600080fd5b505af41580156126d9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126fd9190612d80565b9050600061278682602001518c6001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561274257600080fd5b505afa158015612756573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061277a9190612def565b9063ffffffff612aa916565b905087156127a75760408201516127a490829063ffffffff612aa916565b90505b60006127e6828d6001600160a01b031663b69ef8a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561274257600080fd5b905060006128058261277a86600001518f612aa990919063ffffffff16565b905061283e8d8461282387600001518a612aa990919063ffffffff16565b6020880151612839908a9063ffffffff612aa916565b6122a7565b8b61285a836109cd87600001518561227b90919063ffffffff16565b1461286157fe5b9251929c929b50995090975050505050505050565b303b1590565b600054610100900460ff16806128955750612895612876565b806128a3575060005460ff16155b6128bf5760405162461bcd60e51b815260040161046a90613294565b600054610100900460ff161580156128ea576000805460ff1961ff0019909116610100171660011790555b6128f2612aeb565b6128fa612b6c565b8015611ded576000805461ff001916905550565b600054610100900460ff16806129275750612927612876565b80612935575060005460ff16155b6129515760405162461bcd60e51b815260040161046a90613294565b600054610100900460ff1615801561297c576000805460ff1961ff0019909116610100171660011790555b6097805460ff191690558015611ded576000805461ff001916905550565b6000826129a957506000611f34565b828202828482816129b657fe5b04146122a05760405162461bcd60e51b815260040161046a9061321e565b600080805b6001840154811015612aa25760008460010182815481106129f657fe5b9060005260206000200160009054906101000a90046001600160a01b03169050612a97816001600160a01b031663a4d66daf6040518163ffffffff1660e01b815260040160206040518083038186803b158015612a5257600080fd5b505afa158015612a66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a8a9190612def565b849063ffffffff61227b16565b9250506001016129d9565b5092915050565b60006122a083836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612c46565b600054610100900460ff1680612b045750612b04612876565b80612b12575060005460ff16155b612b2e5760405162461bcd60e51b815260040161046a90613294565b600054610100900460ff161580156128fa576000805460ff1961ff0019909116610100171660011790558015611ded576000805461ff001916905550565b600054610100900460ff1680612b855750612b85612876565b80612b93575060005460ff16155b612baf5760405162461bcd60e51b815260040161046a90613294565b600054610100900460ff16158015612bda576000805460ff1961ff0019909116610100171660011790555b6000612be4611df0565b606580546001600160a01b0319166001600160a01b038316908117909155604051919250906000907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a3508015611ded576000805461ff001916905550565b60008184841115612c6a5760405162461bcd60e51b815260040161046a9190612f49565b505050900390565b610f6e8061341983390190565b60405180606001604052806000815260200160008152602001600081525090565b600060208284031215612cb1578081fd5b81356122a081613403565b600060208284031215612ccd578081fd5b81516122a081613403565b60008060408385031215612cea578081fd5b8235612cf581613403565b946020939093013593505050565b60008060408385031215612cea578182fd5b60008060008060008060c08789031215612d2d578182fd5b8635612d3881613403565b9860208801359850604088013597606081013597506080810135965060a00135945092505050565b600060208284031215612d71578081fd5b815180151581146122a0578182fd5b600060608284031215612d91578081fd5b6040516060810181811067ffffffffffffffff82111715612db0578283fd5b80604052508251815260208301516020820152604083015160408201528091505092915050565b600060208284031215612de8578081fd5b5035919050565b600060208284031215612e00578081fd5b5051919050565b60008060408385031215612e19578182fd5b823591506020830135612e2b81613403565b809150509250929050565b60008060408385031215612e48578182fd5b505080516020909101519092909150565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b03978816815295909616602086015260408501939093526060840191909152608083015260a082015260c081019190915260e00190565b6020808252825182820181905260009190848201906040850190845b81811015612f295783516001600160a01b031683529284019291840191600101612f04565b50909695505050505050565b901515815260200190565b90815260200190565b6000602080835283518082850152825b81811015612f7557858101830151858201604001528201612f59565b81811115612f865783604083870101525b50601f01601f1916929092016040019392505050565b60208082526014908201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604082015260600190565b60208082526026908201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160408201526564647265737360d01b606082015260800190565b6020808252602d908201527f596f75206861766520696e737566666963656e742062616c616e636520666f7260408201526c081d1a1a5cc81c185e5b595b9d609a1b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252602e908201527f54686520756e6465727772697465722063616e6e6f742063726561746520746860408201526d697320637265646974206c696e6560901b606082015260800190565b60408082526010908201526f1d1c985b9cd858dd1a5bdb931a5b5a5d60821b6060820152602081019190915260800190565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b60208082526028908201527f416d6f756e74206973206f76657220746865207065722d7472616e73616374696040820152671bdb881b1a5b5a5d60c21b606082015260800190565b60208082526025908201527f596f7520646f206e6f742062656c6f6e6720746f207468697320637265646974604082015264206c696e6560d81b606082015260800190565b60208082526033908201527f506f6f6c20646f6573206e6f74206861766520656e6f7567682062616c616e6360408201527232903337b9103a3434b990323930bbb237bbb760691b606082015260800190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252818101527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252603a908201527f54686973206c696d69742069732067726561746572207468616e20746865206d60408201527f617820616c6c6f776564206279207468652070726f746f636f6c000000000000606082015260800190565b6040808252601390820152721b585e155b99195c9ddc9a5d195c931a5b5a5d606a1b6060820152602081019190915260800190565b602080825260409082018190527f54686520626f72726f77657220646f6573206e6f74206861766520656e6f7567908201527f6820637265646974206c696d697420666f7220746869732064726177646f776e606082015260800190565b9283526020830191909152604082015260600190565b93845260208401929092526040830152606082015260800190565b6001600160a01b0381168114611ded57600080fdfe608060405234801561001057600080fd5b50610f4e806100206000396000f3fe608060405234801561001057600080fd5b50600436106101da5760003560e01c806396c8df3711610104578063ca3152e5116100a2578063f2fde38b11610071578063f2fde38b146103d6578063f90ce5ba146103fc578063fb1669ca14610404578063fb9eb99014610421576101da565b8063ca3152e514610370578063d8dfeb4514610378578063edbf4ac214610380578063f00db260146103ce576101da565b8063b3969992116100de578063b39699921461033b578063b3b8a9c714610343578063b69ef8a814610360578063c98c05b714610368576101da565b806396c8df371461030e57806399dd8df31461032b578063a4d66daf14610333576101da565b806341f1a1261161017c578063715018a61161014b578063715018a6146102bd5780637957dda3146102c55780637df1f1b9146102e25780638da5cb5b14610306576101da565b806341f1a1261461027357806348e6f29614610290578063500b245e1461029857806361cfbca1146102a0576101da565b806321856b36116101b857806321856b361461020957806327e7b2631461021157806327ea6f2b1461022e5780633059b7c61461024b576101da565b80630d49481d146101df5780631790ebd5146101f95780631935011414610201575b600080fd5b6101e761043e565b60408051918252519081900360200190f35b6101e7610444565b6101e761044a565b6101e7610450565b6101e76004803603602081101561022757600080fd5b5035610456565b6101e76004803603602081101561024457600080fd5b50356104b9565b6102716004803603602081101561026157600080fd5b50356001600160a01b0316610530565b005b6101e76004803603602081101561028957600080fd5b5035610676565b6101e76106d9565b6101e76106df565b6101e7600480360360208110156102b657600080fd5b50356106e5565b610271610748565b6101e7600480360360208110156102db57600080fd5b50356107ea565b6102ea61084d565b604080516001600160a01b039092168252519081900360200190f35b6102ea61085c565b6101e76004803603602081101561032457600080fd5b503561086b565b6101e76108ce565b6101e76108d4565b6101e76108da565b6101e76004803603602081101561035957600080fd5b50356108e0565b6101e7610943565b6101e7610949565b6101e761094f565b6101e7610955565b610271600480360360e081101561039657600080fd5b506001600160a01b03813581169160208101359091169060408101359060608101359060808101359060a08101359060c0013561095b565b6102ea610a59565b610271600480360360208110156103ec57600080fd5b50356001600160a01b0316610a68565b6101e7610b61565b6101e76004803603602081101561041a57600080fd5b5035610b67565b6101e76004803603602081101561043757600080fd5b5035610bca565b609c5481565b60a45481565b60a15481565b60a05481565b6000610460610c2d565b6065546001600160a01b039081169116146104b0576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b5060a681905590565b60006104c361085c565b6001600160a01b0316336001600160a01b031614806104ec57506098546001600160a01b031633145b6105275760405162461bcd60e51b8152600401808060200182810382526022815260200180610ef76022913960400191505060405180910390fd5b50609a81905590565b610538610c2d565b6065546001600160a01b03908116911614610588576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b6000816001600160a01b0316636a83b7e96040518163ffffffff1660e01b815260040160206040518083038186803b1580156105c357600080fd5b505afa1580156105d7573d6000803e3d6000fd5b505050506040513d60208110156105ed57600080fd5b50516040805163095ea7b360e01b81526001600160a01b038581166004830152600019602483015291519293509083169163095ea7b3916044808201926020929091908290030181600087803b15801561064657600080fd5b505af115801561065a573d6000803e3d6000fd5b505050506040513d602081101561067057600080fd5b50505050565b6000610680610c2d565b6065546001600160a01b039081169116146106d0576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b5060a281905590565b609e5481565b60a55481565b60006106ef610c2d565b6065546001600160a01b0390811691161461073f576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b5060a381905590565b610750610c2d565b6065546001600160a01b039081169116146107a0576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b6065546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3606580546001600160a01b0319169055565b60006107f4610c2d565b6065546001600160a01b03908116911614610844576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b5060a581905590565b6097546001600160a01b031681565b6065546001600160a01b031690565b6000610875610c2d565b6065546001600160a01b039081169116146108c5576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b5060a081905590565b609d5481565b609a5481565b609b5481565b60006108ea610c2d565b6065546001600160a01b0390811691161461093a576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b5060a181905590565b609f5481565b60a35481565b60a25481565b60995481565b600054610100900460ff16806109745750610974610c31565b80610982575060005460ff16155b6109bd5760405162461bcd60e51b815260040180806020018281038252602e815260200180610ec9602e913960400191505060405180910390fd5b600054610100900460ff161580156109e8576000805460ff1961ff0019909116610100171660011790555b6109f0610c37565b609780546001600160a01b03808b166001600160a01b03199283161790925560988054928a1692909116919091179055609a869055609b859055609c849055609d839055609e8290554360a6558015610a4f576000805461ff00191690555b5050505050505050565b6098546001600160a01b031681565b610a70610c2d565b6065546001600160a01b03908116911614610ac0576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b6001600160a01b038116610b055760405162461bcd60e51b8152600401808060200182810382526026815260200180610e836026913960400191505060405180910390fd5b6065546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3606580546001600160a01b0319166001600160a01b0392909216919091179055565b60a65481565b6000610b71610c2d565b6065546001600160a01b03908116911614610bc1576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b50609f81905590565b6000610bd4610c2d565b6065546001600160a01b03908116911614610c24576040805162461bcd60e51b81526020600482018190526024820152600080516020610ea9833981519152604482015290519081900360640190fd5b5060a481905590565b3390565b303b1590565b600054610100900460ff1680610c505750610c50610c31565b80610c5e575060005460ff16155b610c995760405162461bcd60e51b815260040180806020018281038252602e815260200180610ec9602e913960400191505060405180910390fd5b600054610100900460ff16158015610cc4576000805460ff1961ff0019909116610100171660011790555b610ccc610ce9565b610cd4610d89565b8015610ce6576000805461ff00191690555b50565b600054610100900460ff1680610d025750610d02610c31565b80610d10575060005460ff16155b610d4b5760405162461bcd60e51b815260040180806020018281038252602e815260200180610ec9602e913960400191505060405180910390fd5b600054610100900460ff16158015610cd4576000805460ff1961ff0019909116610100171660011790558015610ce6576000805461ff001916905550565b600054610100900460ff1680610da25750610da2610c31565b80610db0575060005460ff16155b610deb5760405162461bcd60e51b815260040180806020018281038252602e815260200180610ec9602e913960400191505060405180910390fd5b600054610100900460ff16158015610e16576000805460ff1961ff0019909116610100171660011790555b6000610e20610c2d565b606580546001600160a01b0319166001600160a01b038316908117909155604051919250906000907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a3508015610ce6576000805461ff00191690555056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645265737472696374656420746f206f776e6572206f7220756e646572777269746572a26469706673582212201bbb00c0cf24d22536869cc2da2c9fa399e4da9e7b2e0bf38f21a36f9c56b95b64736f6c63430006080033a26469706673582212209d1d4058d768ff5c1631f71e041e22e9cc5209d9a65ed39a26d40ed47b48114c64736f6c63430006080033
[ 0, 4, 7, 9, 16, 5, 2 ]
0x43cf2d93f0a46f39eb16cc92d1e10ba90ad21183
pragma solidity 0.6.6; 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. * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract 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(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is IERC20, Ownable { 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 {totalSupply} {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 () public { _name = 'Yit.Finance'; _symbol = 'YIT'; _decimals = 18; _mint(msg.sender, 50000000000000000000000); } /** * @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(msg.sender, 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(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`. */ 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 Destroys `amount` tokens from `account`, reducing the total supply */ function burn(uint256 _amount) public onlyOwner { _burn(msg.sender, _amount); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
0x608060405234801561001057600080fd5b50600436106100f55760003560e01c806370a0823111610097578063a457c2d711610066578063a457c2d7146102ca578063a9059cbb146102f6578063dd62ed3e14610322578063f2fde38b14610350576100f5565b806370a0823114610270578063715018a6146102965780638da5cb5b1461029e57806395d89b41146102c2576100f5565b806323b872dd116100d357806323b872dd146101d1578063313ce56714610207578063395093511461022557806342966c6814610251576100f5565b806306fdde03146100fa578063095ea7b31461017757806318160ddd146101b7575b600080fd5b610102610376565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561013c578181015183820152602001610124565b50505050905090810190601f1680156101695780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101a36004803603604081101561018d57600080fd5b506001600160a01b03813516906020013561040c565b604080519115158252519081900360200190f35b6101bf610422565b60408051918252519081900360200190f35b6101a3600480360360608110156101e757600080fd5b506001600160a01b03813581169160208101359091169060400135610428565b61020f610497565b6040805160ff9092168252519081900360200190f35b6101a36004803603604081101561023b57600080fd5b506001600160a01b0381351690602001356104a0565b61026e6004803603602081101561026757600080fd5b50356104dc565b005b6101bf6004803603602081101561028657600080fd5b50356001600160a01b0316610548565b61026e610563565b6102a661060c565b604080516001600160a01b039092168252519081900360200190f35b61010261061b565b6101a3600480360360408110156102e057600080fd5b506001600160a01b03813516906020013561067c565b6101a36004803603604081101561030c57600080fd5b506001600160a01b0381351690602001356106d1565b6101bf6004803603604081101561033857600080fd5b506001600160a01b03813581169160200135166106de565b61026e6004803603602081101561036657600080fd5b50356001600160a01b0316610709565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104025780601f106103d757610100808354040283529160200191610402565b820191906000526020600020905b8154815290600101906020018083116103e557829003601f168201915b5050505050905090565b6000610419338484610808565b50600192915050565b60035490565b60006104358484846108f4565b61048d843361048885604051806060016040528060288152602001610d58602891396001600160a01b038a166000908152600260209081526040808320338452909152902054919063ffffffff610a5d16565b610808565b5060019392505050565b60065460ff1690565b3360008181526002602090815260408083206001600160a01b03871684529091528120549091610419918590610488908663ffffffff610af416565b6000546001600160a01b0316331461053b576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6105453382610b55565b50565b6001600160a01b031660009081526001602052604090205490565b6000546001600160a01b031633146105c2576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031690565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104025780601f106103d757610100808354040283529160200191610402565b6000610419338461048885604051806060016040528060258152602001610dea602591393360009081526002602090815260408083206001600160a01b038d168452909152902054919063ffffffff610a5d16565b60006104193384846108f4565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b6000546001600160a01b03163314610768576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b0381166107ad5760405162461bcd60e51b8152600401808060200182810382526026815260200180610cea6026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03831661084d5760405162461bcd60e51b8152600401808060200182810382526024815260200180610dc66024913960400191505060405180910390fd5b6001600160a01b0382166108925760405162461bcd60e51b8152600401808060200182810382526022815260200180610d106022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166109395760405162461bcd60e51b8152600401808060200182810382526025815260200180610da16025913960400191505060405180910390fd5b6001600160a01b03821661097e5760405162461bcd60e51b8152600401808060200182810382526023815260200180610ca56023913960400191505060405180910390fd5b610989838383610c5d565b6109cc81604051806060016040528060268152602001610d32602691396001600160a01b038616600090815260016020526040902054919063ffffffff610a5d16565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610a01908263ffffffff610af416565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610aec5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610ab1578181015183820152602001610a99565b50505050905090810190601f168015610ade5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082820183811015610b4e576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6001600160a01b038216610b9a5760405162461bcd60e51b8152600401808060200182810382526021815260200180610d806021913960400191505060405180910390fd5b610ba682600083610c5d565b610be981604051806060016040528060228152602001610cc8602291396001600160a01b038516600090815260016020526040902054919063ffffffff610a5d16565b6001600160a01b038316600090815260016020526040902055600354610c15908263ffffffff610c6216565b6003556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b505050565b6000610b4e83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610a5d56fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e63654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220b0ba05d7d04446265951fdd660631e547f2a9c9cea058eced101b1f00cb248f564736f6c63430006060033
[ 38 ]
0x445830226347ef75867502e00e8d663842114f19
pragma solidity 0.6.11; pragma experimental ABIEncoderV2; struct FullAbsoluteTokenAmount { AbsoluteTokenAmountMeta base; AbsoluteTokenAmountMeta[] underlying; } struct AbsoluteTokenAmountMeta { AbsoluteTokenAmount absoluteTokenAmount; ERC20Metadata erc20metadata; } struct ERC20Metadata { string name; string symbol; uint8 decimals; } struct AdapterBalance { bytes32 protocolAdapterName; AbsoluteTokenAmount[] absoluteTokenAmounts; } struct AbsoluteTokenAmount { address token; uint256 amount; } struct Component { address token; uint256 rate; } struct TransactionData { Action[] actions; TokenAmount[] inputs; Fee fee; AbsoluteTokenAmount[] requiredOutputs; uint256 nonce; } struct Action { bytes32 protocolAdapterName; ActionType actionType; TokenAmount[] tokenAmounts; bytes data; } struct TokenAmount { address token; uint256 amount; AmountType amountType; } struct Fee { uint256 share; address beneficiary; } enum ActionType { None, Deposit, Withdraw } enum AmountType { None, Relative, Absolute } abstract contract ProtocolAdapter { /** * @dev MUST return amount and type of the given token * locked on the protocol by the given account. */ function getBalance( address token, address account ) public view virtual returns (uint256); } contract WethAdapter is ProtocolAdapter { /** * @return Amount of WETH held by the given account. * @dev Implementation of ProtocolAdapter abstract contract function. */ function getBalance( address token, address account ) public view override returns (uint256) { return ERC20(token).balanceOf(account); } } abstract contract InteractiveAdapter is ProtocolAdapter { uint256 internal constant DELIMITER = 1e18; address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /** * @dev The function must deposit assets to the protocol. * @return MUST return assets to be sent back to the `msg.sender`. */ function deposit( TokenAmount[] memory tokenAmounts, bytes memory data ) public payable virtual returns (address[] memory); /** * @dev The function must withdraw assets from the protocol. * @return MUST return assets to be sent back to the `msg.sender`. */ function withdraw( TokenAmount[] memory tokenAmounts, bytes memory data ) public payable virtual returns (address[] memory); function getAbsoluteAmountDeposit( TokenAmount memory tokenAmount ) internal view virtual returns (uint256) { address token = tokenAmount.token; uint256 amount = tokenAmount.amount; AmountType amountType = tokenAmount.amountType; require( amountType == AmountType.Relative || amountType == AmountType.Absolute, "IA: bad amount type" ); if (amountType == AmountType.Relative) { require(amount <= DELIMITER, "IA: bad amount"); uint256 balance; if (token == ETH) { balance = address(this).balance; } else { balance = ERC20(token).balanceOf(address(this)); } if (amount == DELIMITER) { return balance; } else { return mul(balance, amount) / DELIMITER; } } else { return amount; } } function getAbsoluteAmountWithdraw( TokenAmount memory tokenAmount ) internal view virtual returns (uint256) { address token = tokenAmount.token; uint256 amount = tokenAmount.amount; AmountType amountType = tokenAmount.amountType; require( amountType == AmountType.Relative || amountType == AmountType.Absolute, "IA: bad amount type" ); if (amountType == AmountType.Relative) { require(amount <= DELIMITER, "IA: bad amount"); uint256 balance = getBalance(token, address(this)); if (amount == DELIMITER) { return balance; } else { return mul(balance, amount) / DELIMITER; } } else { return amount; } } function mul( uint256 a, uint256 b ) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "IA: mul overflow"); return c; } } interface WETH9 { function deposit() external payable; function withdraw(uint256) external; } contract WethInteractiveAdapter is InteractiveAdapter, WethAdapter { address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /** * @notice Wraps Ether in Wrapped Ether. * @param tokenAmounts Array with one element - TokenAmount struct with * ETH address (0xEeee...EEeE), ETH amount to be deposited, and amount type. * @return tokensToBeWithdrawn Array with one element - WETH token address. * @dev Implementation of InteractiveAdapter function. */ function deposit( TokenAmount[] memory tokenAmounts, bytes memory ) public payable override returns (address[] memory tokensToBeWithdrawn) { require(tokenAmounts.length == 1, "WIA: should be 1 tokenAmount"); require(tokenAmounts[0].token == ETH, "WIA: should be ETH"); uint256 amount = getAbsoluteAmountDeposit(tokenAmounts[0]); tokensToBeWithdrawn = new address[](1); tokensToBeWithdrawn[0] = WETH; try WETH9(WETH).deposit{value: amount}() { // solhint-disable-line no-empty-blocks } catch Error(string memory reason) { revert(reason); } catch { revert("WIA: deposit fail"); } } /** * @notice Unwraps Ether from Wrapped Ether. * @param tokenAmounts Array with one element - TokenAmount struct with * WETH token address, WETH token amount to be redeemed, and amount type. * @return tokensToBeWithdrawn Array with one element - ETH address (0xEeee...EEeE). * @dev Implementation of InteractiveAdapter function. */ function withdraw( TokenAmount[] memory tokenAmounts, bytes memory ) public payable override returns (address[] memory tokensToBeWithdrawn) { require(tokenAmounts.length == 1, "WIA: should be 1 tokenAmount"); require(tokenAmounts[0].token == WETH, "WIA: should be WETH"); uint256 amount = getAbsoluteAmountWithdraw(tokenAmounts[0]); tokensToBeWithdrawn = new address[](1); tokensToBeWithdrawn[0] = ETH; try WETH9(WETH).withdraw(amount) { // solhint-disable-line no-empty-blocks } catch Error(string memory reason) { revert(reason); } catch { revert("WIA: withdraw fail"); } } } interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); 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) external view returns (uint256); function allowance(address, address) external view returns (uint256); }
0x6080604052600436106100345760003560e01c806328ffb83d14610039578063387b817414610062578063d4fac45d14610075575b600080fd5b61004c610047366004610a28565b6100a2565b6040516100599190610b2d565b60405180910390f35b61004c610070366004610a28565b610308565b34801561008157600080fd5b506100956100903660046109f4565b61051d565b6040516100599190610db0565b606082516001146100e8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610cd4565b60405180910390fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee73ffffffffffffffffffffffffffffffffffffffff168360008151811061012057fe5b60200260200101516000015173ffffffffffffffffffffffffffffffffffffffff1614610179576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610c66565b60006101988460008151811061018b57fe5b60200260200101516105cb565b6040805160018082528183019092529192506020808301908036833701905050915073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2826000815181106101dc57fe5b602002602001019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff168152505073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff1663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b15801561027257600080fd5b505af193505050508015610284575060015b61030157610290610e06565b8061029b57506102cf565b806040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df9190610b87565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610d42565b5092915050565b60608251600114610345576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610cd4565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc273ffffffffffffffffffffffffffffffffffffffff168360008151811061037d57fe5b60200260200101516000015173ffffffffffffffffffffffffffffffffffffffff16146103d6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610bf8565b60006103f5846000815181106103e857fe5b60200260200101516107bd565b6040805160018082528183019092529192506020808301908036833701905050915073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee8260008151811061043957fe5b73ffffffffffffffffffffffffffffffffffffffff909216602092830291909101909101526040517f2e1a7d4d00000000000000000000000000000000000000000000000000000000815273c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290632e1a7d4d906104ae908490600401610db0565b600060405180830381600087803b1580156104c857600080fd5b505af19250505080156104d9575060015b610301576104e5610e06565b8061029b57506040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610d0b565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815260009073ffffffffffffffffffffffffffffffffffffffff8416906370a0823190610572908590600401610b0c565b60206040518083038186803b15801561058a57600080fd5b505afa15801561059e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105c29190610af4565b90505b92915050565b805160208201516040830151600092919060018160028111156105ea57fe5b1480610601575060028160028111156105ff57fe5b145b610637576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610c2f565b600181600281111561064557fe5b14156107ae57670de0b6b3a764000082111561068d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610c9d565b600073ffffffffffffffffffffffffffffffffffffffff841673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156106c857504761076d565b6040517f70a0823100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516906370a082319061071a903090600401610b0c565b60206040518083038186803b15801561073257600080fd5b505afa158015610746573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061076a9190610af4565b90505b670de0b6b3a76400008314156107885793506107b892505050565b670de0b6b3a764000061079b828561088b565b816107a257fe5b049450505050506107b8565b5091506107b89050565b919050565b805160208201516040830151600092919060018160028111156107dc57fe5b14806107f3575060028160028111156107f157fe5b145b610829576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610c2f565b600181600281111561083757fe5b14156107ae57670de0b6b3a764000082111561087f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610c9d565b600061076a843061051d565b60008261089a575060006105c5565b828202828482816108a757fe5b04146105c2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100df90610d79565b803573ffffffffffffffffffffffffffffffffffffffff811681146105c557600080fd5b600082601f830112610913578081fd5b813567ffffffffffffffff811115610929578182fd5b61095a60207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f84011601610db9565b915080825283602082850101111561097157600080fd5b8060208401602084013760009082016020015292915050565b60006060828403121561099b578081fd5b6109a56060610db9565b9050813573ffffffffffffffffffffffffffffffffffffffff811681146109cb57600080fd5b8152602082810135908201526040820135600381106109e957600080fd5b604082015292915050565b60008060408385031215610a06578182fd5b610a1084846108df565b9150610a1f84602085016108df565b90509250929050565b60008060408385031215610a3a578182fd5b823567ffffffffffffffff80821115610a51578384fd5b81850186601f820112610a62578485fd5b80359250610a77610a7284610de0565b610db9565b808482526020808301925080840160608b83828a028801011115610a9957898afd5b8995505b87861015610ac557610aaf8c8361098a565b8552600195909501949382019390810190610a9d565b50919750880135945050505080821115610add578283fd5b50610aea85828601610903565b9150509250929050565b600060208284031215610b05578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6020808252825182820181905260009190848201906040850190845b81811015610b7b57835173ffffffffffffffffffffffffffffffffffffffff1683529284019291840191600101610b49565b50909695505050505050565b6000602080835283518082850152825b81811015610bb357858101830151858201604001528201610b97565b81811115610bc45783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b60208082526013908201527f5749413a2073686f756c64206265205745544800000000000000000000000000604082015260600190565b60208082526013908201527f49413a2062616420616d6f756e74207479706500000000000000000000000000604082015260600190565b60208082526012908201527f5749413a2073686f756c64206265204554480000000000000000000000000000604082015260600190565b6020808252600e908201527f49413a2062616420616d6f756e74000000000000000000000000000000000000604082015260600190565b6020808252601c908201527f5749413a2073686f756c64206265203120746f6b656e416d6f756e7400000000604082015260600190565b60208082526012908201527f5749413a207769746864726177206661696c0000000000000000000000000000604082015260600190565b60208082526011908201527f5749413a206465706f736974206661696c000000000000000000000000000000604082015260600190565b60208082526010908201527f49413a206d756c206f766572666c6f7700000000000000000000000000000000604082015260600190565b90815260200190565b60405181810167ffffffffffffffff81118282101715610dd857600080fd5b604052919050565b600067ffffffffffffffff821115610df6578081fd5b5060209081020190565b60e01c90565b600060443d1015610e1657610ee8565b600481823e6308c379a0610e2a8251610e00565b14610e3457610ee8565b6040517ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3d016004823e80513d67ffffffffffffffff8160248401118184111715610e825750505050610ee8565b82840191508151925080831115610e9c5750505050610ee8565b503d83016020838301011115610eb457505050610ee8565b601f919091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01681016020016040529150505b9056fea2646970667358221220f4800f8ce955744489a68488faf92bb6bbff77a13e66a227341fbc0ad68c543e64736f6c634300060b0033
[ 9, 12 ]
0x44863f5b7AAb7ceE181C0d84E244540125eF7AF7
pragma solidity 0.7.4; interface IArbitrable { /** * @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(IArbitrator indexed _arbitrator, uint256 indexed _disputeID, uint256 _ruling); /** * @dev Give 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 "Not able/wanting to make a decision". */ function rule(uint256 _disputeID, uint256 _ruling) external; } interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} /** * @dev To be emitted when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint256 _choices, bytes calldata _extraData) external payable returns (uint256 disputeID); /** * @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function arbitrationCost(bytes calldata _extraData) external view returns (uint256 cost); /** * @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint256 _disputeID, bytes calldata _extraData) external payable; /** * @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function appealCost(uint256 _disputeID, bytes calldata _extraData) external view returns (uint256 cost); /** * @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0). * @param _disputeID ID of the dispute. * @return start The start of the period. * @return end The end of the period. */ function appealPeriod(uint256 _disputeID) external view returns (uint256 start, uint256 end); /** * @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint256 _disputeID) external view returns (DisputeStatus status); /** * @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint256 _disputeID) external view returns (uint256 ruling); } interface IEvidence { /** * @dev To be emitted when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint256 indexed _metaEvidenceID, string _evidence); /** * @dev To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence( IArbitrator indexed _arbitrator, uint256 indexed _evidenceGroupID, address indexed _party, string _evidence ); /** * @dev To be emitted when a dispute is created to link the correct meta-evidence to the disputeID. * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute( IArbitrator indexed _arbitrator, uint256 indexed _disputeID, uint256 _metaEvidenceID, uint256 _evidenceGroupID ); } library CappedMath { uint constant private UINT_MAX = 2**256 - 1; /** * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow. */ function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */ function mulCap(uint _a, uint _b) internal pure returns (uint) { // 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; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } 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; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { /** * @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) { // 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); } } } } contract Linguo is IArbitrable, IEvidence { using CappedMath for uint256; /* *** Contract variables *** */ uint8 public constant VERSION_ID = 0; // Value that represents the version of the contract. The value is incremented each time the new version is deployed. Range for LinguoETH: 0-127, LinguoToken: 128-255. uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. uint256 private constant NOT_PAYABLE_VALUE = (2**256 - 2) / 2; // A value depositors won't be able to pay. enum Status {Created, Assigned, AwaitingReview, DisputeCreated, Resolved} enum Party { None, // Party that is mapped with a 0 dispute ruling. Translator, // Party performing translation task. Challenger // Party challenging translated text in the review period. } // Arrays of 3 elements in the Task and Round structs map to the parties. Index "0" is not used, "1" is used for the translator and "2" for the challenger. struct Task { uint256 submissionTimeout; // Time in seconds allotted for submitting a translation. The end of this period is considered a deadline. uint256 minPrice; // Minimum price for the translation. When the task is created it has this minimum price that gradually increases such that it reaches the maximum price at the deadline. uint256 maxPrice; // Maximum price for the translation and also the value that must be deposited by the requester. Status status; // Status of the task. uint256 lastInteraction; // The time of the last action performed on the task. Note that lastInteraction is updated only during timeout-related actions such as the creation of the task and the submission of the translation. address payable requester; // The party requesting the translation. uint256 requesterDeposit; // The deposit requester makes when creating the task. Once the task is assigned this deposit will be partially reimbursed and its value replaced by the task price. uint256 sumDeposit; // The sum of the deposits of the translator and the challenger, if any. This value (minus arbitration fees) will be paid to the party that wins the dispute. address payable[3] parties; // Translator and challenger of the task. uint256 disputeID; // The ID of the dispute created in the arbitrator contract. Round[] rounds; // Tracks each appeal round of a dispute. uint256 ruling; // Ruling given to the dispute of the task by the arbitrator. } struct Round { uint256[3] paidFees; // Tracks the fees paid by each side in this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint256 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 => uint256[3]) contributions; // Maps contributors to their contributions for each side. } address public governor = msg.sender; // The governor of the contract. IArbitrator public immutable arbitrator; // The address of the ERC-792 Arbitrator. bytes public arbitratorExtraData; // Extra data to allow creating a dispute on the arbitrator. uint256 public reviewTimeout; // Time in seconds, during which the submitted translation can be challenged. // All multipliers below are in basis points. uint256 public translationMultiplier; // Multiplier for calculating the value of the deposit translator must pay to self-assign a task. uint256 public challengeMultiplier; // Multiplier for calculating the value of the deposit challenger must pay to challenge a translation. uint256 public sharedStakeMultiplier; // Multiplier for calculating the appeal fee that must be paid by the submitter in the case where there isn't a winner and loser (e.g. when the arbitrator ruled "refuse to arbitrate"). uint256 public winnerStakeMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round. uint256 public loserStakeMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round. Task[] public tasks; // Stores all created tasks. mapping(uint256 => uint256) public disputeIDtoTaskID; // Maps a disputeID to its respective task. /* *** Events *** */ /** @dev To be emitted when a new task is created. * @param _taskID The ID of the newly created task. * @param _requester The address that created the task. * @param _timestamp When the task was created. */ event TaskCreated(uint256 indexed _taskID, address indexed _requester, uint256 _timestamp); /** @dev To be emitted when a translator assigns a task to himself. * @param _taskID The ID of the assigned task. * @param _translator The address that was assigned to the task. * @param _price The task price at the moment it was assigned. * @param _timestamp When the task was assigned. */ event TaskAssigned(uint256 indexed _taskID, address indexed _translator, uint256 _price, uint256 _timestamp); /** @dev To be emitted when a translation is submitted. * @param _taskID The ID of the respective task. * @param _translator The address that performed the translation. * @param _translatedText A URI to the translated text. * @param _timestamp When the translation was submitted. */ event TranslationSubmitted( uint256 indexed _taskID, address indexed _translator, string _translatedText, uint256 _timestamp ); /** @dev To be emitted when a translation is challenged. * @param _taskID The ID of the respective task. * @param _challenger The address of the challenger. * @param _timestamp When the task was challenged. */ event TranslationChallenged(uint256 indexed _taskID, address indexed _challenger, uint256 _timestamp); /** @dev To be emitted when a task is resolved, either by the translation being accepted, the requester being reimbursed or a dispute being settled. * @param _taskID The ID of the respective task. * @param _reason Short description of what caused the task to be solved. One of: 'translation-accepted' | 'requester-reimbursed' | 'dispute-settled' * @param _timestamp When the task was resolved. */ event TaskResolved(uint256 indexed _taskID, string _reason, uint256 _timestamp); /** @dev To be emitted when someone contributes to the appeal process. * @param _taskID The ID of the respective task. * @param _party The party which received the contribution. * @param _contributor The address of the contributor. * @param _amount The amount contributed. */ event AppealContribution(uint256 indexed _taskID, Party _party, address indexed _contributor, uint256 _amount); /** @dev To be emitted when the appeal fees of one of the parties are fully funded. * @param _taskID The ID of the respective task. * @param _party The party that is fully funded. */ event HasPaidAppealFee(uint256 indexed _taskID, Party _party); /* *** Modifiers *** */ modifier onlyGovernor() { require(msg.sender == governor, "Only governor is allowed to perform this."); _; } /** @dev Constructor. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. * @param _reviewTimeout Time in seconds during which a translation can be challenged. * @param _translationMultiplier Multiplier for calculating translator's deposit. In basis points. * @param _challengeMultiplier Multiplier for calculating challenger's deposit. In basis points. * @param _sharedStakeMultiplier Multiplier of the appeal cost that submitter must pay for a round when there is no winner/loser in the previous round. In basis points. * @param _winnerStakeMultiplier Multiplier of the appeal cost that the winner has to pay for a round. In basis points. * @param _loserStakeMultiplier Multiplier of the appeal cost that the loser has to pay for a round. In basis points. */ constructor( IArbitrator _arbitrator, bytes memory _arbitratorExtraData, uint256 _reviewTimeout, uint256 _translationMultiplier, uint256 _challengeMultiplier, uint256 _sharedStakeMultiplier, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier ) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; reviewTimeout = _reviewTimeout; translationMultiplier = _translationMultiplier; challengeMultiplier = _challengeMultiplier; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } // ******************** // // * Governance * // // ******************** // /** @dev Changes the governor of this contract. * @param _governor A new governor. */ function changeGovernor(address _governor) public onlyGovernor { governor = _governor; } /** @dev Changes the time allocated for the review phase. * @param _reviewTimeout A new value of the time allotted for reviewing a translation. In seconds. */ function changeReviewTimeout(uint256 _reviewTimeout) public onlyGovernor { reviewTimeout = _reviewTimeout; } /** @dev Changes the multiplier for translators' deposit. * @param _translationMultiplier A new value of the multiplier for calculating translator's deposit. In basis points. */ function changeTranslationMultiplier(uint256 _translationMultiplier) public onlyGovernor { translationMultiplier = _translationMultiplier; } /** @dev Changes the multiplier for challengers' deposit. * @param _challengeMultiplier A new value of the multiplier for calculating challenger's deposit. In basis points. */ function changeChallengeMultiplier(uint256 _challengeMultiplier) public onlyGovernor { challengeMultiplier = _challengeMultiplier; } /** @dev Changes the percentage of arbitration fees that must be paid by parties as a fee stake if there was no winner and loser in the previous round. * @param _sharedStakeMultiplier A new value of the multiplier of the appeal cost in case where there was no winner/loser in previous round. In basis point. */ function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) public onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Changes the percentage of arbitration fees that must be paid as a fee stake by the party that won the previous round. * @param _winnerStakeMultiplier A new value of the multiplier of the appeal cost that the winner of the previous round has to pay. In basis points. */ function changeWinnerStakeMultiplier(uint256 _winnerStakeMultiplier) public onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Changes the percentage of arbitration fees that must be paid as a fee stake by the party that lost the previous round. * @param _loserStakeMultiplier A new value for the multiplier of the appeal cost that the party that lost the previous round has to pay. In basis points. */ function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) public onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } // **************************** // // * Modifying the state * // // **************************** // /** @dev Creates a task based on provided details. Requires a value of maximum price to be deposited. * @param _deadline The deadline for the translation to be completed. * @param _minPrice A minimum price of the translation. In wei. * @param _metaEvidence A URI of a meta-evidence object for task submission. * @return taskID The ID of the created task. */ function createTask( uint256 _deadline, uint256 _minPrice, string calldata _metaEvidence ) external payable returns (uint256 taskID) { require(msg.value >= _minPrice, "Deposited value should be greater than or equal to the min price."); require(_deadline > block.timestamp, "The deadline should be in the future."); taskID = tasks.length; Task storage task = tasks.push(); task.submissionTimeout = _deadline - block.timestamp; task.minPrice = _minPrice; task.maxPrice = msg.value; task.lastInteraction = block.timestamp; task.requester = msg.sender; task.requesterDeposit = msg.value; emit MetaEvidence(taskID, _metaEvidence); emit TaskCreated(taskID, msg.sender, block.timestamp); } /** @dev Assigns a specific task to the sender. Requires a translator's deposit. * Note that the deposit should be a little higher than the required value because of the price increase during the time the transaction is mined. The surplus will be reimbursed. * @param _taskID The ID of the task. */ function assignTask(uint256 _taskID) external payable { Task storage task = tasks[_taskID]; require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 translatorDeposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); require(task.status == Status.Created, "Task has already been assigned or reimbursed."); require(msg.value >= translatorDeposit, "Not enough ETH to reach the required deposit value."); task.parties[uint256(Party.Translator)] = msg.sender; task.status = Status.Assigned; uint256 remainder = task.maxPrice - price; task.requester.send(remainder); // Update requester's deposit since we reimbursed him the difference between maximum and actual price. task.requesterDeposit = price; task.sumDeposit = translatorDeposit; remainder = msg.value - translatorDeposit; msg.sender.send(remainder); emit TaskAssigned(_taskID, msg.sender, price, block.timestamp); } /** @dev Submits translated text for a specific task. * @param _taskID The ID of the task. * @param _translation A URI to the translated text. */ function submitTranslation(uint256 _taskID, string calldata _translation) external { Task storage task = tasks[_taskID]; require( task.status == Status.Assigned, "The task is either not assigned or translation has already been submitted." ); require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); require( msg.sender == task.parties[uint256(Party.Translator)], "Can't submit translation to a task that wasn't assigned to you." ); task.status = Status.AwaitingReview; task.lastInteraction = block.timestamp; emit TranslationSubmitted(_taskID, msg.sender, _translation, block.timestamp); } /** @dev Reimburses the requester if no one picked the task or the translator failed to submit the translation before deadline. * @param _taskID The ID of the task. */ function reimburseRequester(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status < Status.AwaitingReview, "Can't reimburse if translation was submitted."); require( block.timestamp - task.lastInteraction > task.submissionTimeout, "Can't reimburse if the deadline hasn't passed yet." ); task.status = Status.Resolved; // Requester gets his deposit back and also the deposit of the translator, if there was one. // Note that sumDeposit can't contain challenger's deposit until the task is in DisputeCreated status. uint256 amount = task.requesterDeposit + task.sumDeposit; task.requester.send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "requester-reimbursed", block.timestamp); } /** @dev Pays the translator for completed task if no one challenged the translation during the review period. * @param _taskID The ID of the task. */ function acceptTranslation(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction > reviewTimeout, "The review phase hasn't passed yet."); task.status = Status.Resolved; // Translator gets the price of the task and his deposit back. Note that sumDeposit can't contain challenger's deposit until the task has DisputeCreated status. uint256 amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "translation-accepted", block.timestamp); } /** @dev Challenges the translation of a specific task. Requires challenger's deposit. * @param _taskID The ID of the task. * @param _evidence A link to evidence using its URI. Ignored if not provided. */ function challengeTranslation(uint256 _taskID, string calldata _evidence) external payable { Task storage task = tasks[_taskID]; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 challengeDeposit = arbitrationCost.addCap( (challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR ); require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction <= reviewTimeout, "The review phase has already passed."); require(msg.value >= challengeDeposit, "Not enough ETH to cover challenge deposit."); task.status = Status.DisputeCreated; task.parties[uint256(Party.Challenger)] = msg.sender; task.disputeID = arbitrator.createDispute{value: arbitrationCost}(2, arbitratorExtraData); disputeIDtoTaskID[task.disputeID] = _taskID; task.rounds.push(); task.sumDeposit = task.sumDeposit.addCap(challengeDeposit).subCap(arbitrationCost); uint256 remainder = msg.value - challengeDeposit; msg.sender.send(remainder); emit Dispute(arbitrator, task.disputeID, _taskID, _taskID); emit TranslationChallenged(_taskID, msg.sender, block.timestamp); if (bytes(_evidence).length > 0) emit Evidence(arbitrator, _taskID, msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if all sides are fully funded. * @param _taskID The ID of challenged task. * @param _side The party that pays the appeal fee. */ function fundAppeal(uint256 _taskID, Party _side) external payable { Task storage task = tasks[_taskID]; require( _side == Party.Translator || _side == Party.Challenger, "Recipient must be either the translator or challenger." ); require(task.status == Status.DisputeCreated, "No dispute to appeal."); require( arbitrator.disputeStatus(task.disputeID) == IArbitrator.DisputeStatus.Appealable, "Dispute is not appealable." ); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(task.disputeID); require( block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Funding must be made within the appeal period." ); uint256 winner = arbitrator.currentRuling(task.disputeID); uint256 multiplier; if (winner == uint256(_side)) { multiplier = winnerStakeMultiplier; } else if (winner == 0) { multiplier = sharedStakeMultiplier; } else { require( block.timestamp - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) / 2, "The loser must pay during the first half of the appeal period." ); multiplier = loserStakeMultiplier; } Round storage round = task.rounds[task.rounds.length - 1]; require(!round.hasPaid[uint256(_side)], "Appeal fee has already been paid."); uint256 appealCost = arbitrator.appealCost(task.disputeID, arbitratorExtraData); uint256 totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution; // Amount contributed. uint256 remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution( msg.value, totalCost.subCap(round.paidFees[uint256(_side)]) ); round.contributions[msg.sender][uint256(_side)] += contribution; round.paidFees[uint256(_side)] += contribution; emit AppealContribution(_taskID, _side, msg.sender, contribution); // Add contribution to reward when the fee funding is successful, otherwise it can be withdrawn later. if (round.paidFees[uint256(_side)] >= totalCost) { round.hasPaid[uint256(_side)] = true; round.feeRewards += round.paidFees[uint256(_side)]; emit HasPaidAppealFee(_taskID, _side); } // Reimburse leftover ETH. msg.sender.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. // Create an appeal if each side is funded. if (round.hasPaid[uint256(Party.Translator)] && round.hasPaid[uint256(Party.Challenger)]) { arbitrator.appeal{value: appealCost}(task.disputeID, arbitratorExtraData); task.rounds.push(); round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @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(uint256 _available, uint256 _requiredAmount) internal pure returns (uint256 taken, uint256 remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Withdraws contributions of appeal rounds. Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions. * @param _taskID The ID of the associated task. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( address payable _beneficiary, uint256 _taskID, uint256 _round ) public { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; require(task.status == Status.Resolved, "The task should be resolved."); uint256 reward; if (!round.hasPaid[uint256(Party.Translator)] || !round.hasPaid[uint256(Party.Challenger)]) { // Allow to reimburse if funding was unsuccessful. reward = round.contributions[_beneficiary][uint256(Party.Translator)] + round.contributions[_beneficiary][uint256(Party.Challenger)]; round.contributions[_beneficiary][uint256(Party.Translator)] = 0; round.contributions[_beneficiary][uint256(Party.Challenger)] = 0; } else if (task.ruling == uint256(Party.None)) { // Reimburse unspent fees proportionally if there is no winner and loser. uint256 rewardTranslator = round.paidFees[uint256(Party.Translator)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Translator)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; uint256 rewardChallenger = round.paidFees[uint256(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; reward = rewardTranslator + rewardChallenger; round.contributions[_beneficiary][uint256(Party.Translator)] = 0; round.contributions[_beneficiary][uint256(Party.Challenger)] = 0; } else { // Reward the winner. reward = round.paidFees[task.ruling] > 0 ? (round.contributions[_beneficiary][task.ruling] * round.feeRewards) / round.paidFees[task.ruling] : 0; round.contributions[_beneficiary][task.ruling] = 0; } _beneficiary.send(reward); // It is the user's responsibility to accept ETH. } /** @dev Withdraws contributions of multiple appeal rounds at once. This function is O(n) where n is the number of rounds. This could exceed the gas limit, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions. * @param _taskID The ID of the associated task. * @param _cursor The round from where to start withdrawing. * @param _count The number of rounds to iterate. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchRoundWithdraw( address payable _beneficiary, uint256 _taskID, uint256 _cursor, uint256 _count ) public { Task storage task = tasks[_taskID]; for (uint256 i = _cursor; i < task.rounds.length && (_count == 0 || i < _cursor + _count); i++) withdrawFeesAndRewards(_beneficiary, _taskID, i); } /** @dev Gives the ruling for a dispute. Can only 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 and to invert the ruling in the case a party loses from lack of appeal fees funding. * @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(uint256 _disputeID, uint256 _ruling) external override { Party resultRuling = Party(_ruling); uint256 taskID = disputeIDtoTaskID[_disputeID]; Task storage task = tasks[taskID]; Round storage round = task.rounds[task.rounds.length - 1]; require(msg.sender == address(arbitrator), "Must be called by the arbitrator."); require(task.status == Status.DisputeCreated, "The dispute has already been resolved."); // If only one side paid its fees we assume the ruling to be in its favor. if (round.hasPaid[uint256(Party.Translator)] == true) resultRuling = Party.Translator; else if (round.hasPaid[uint256(Party.Challenger)] == true) resultRuling = Party.Challenger; emit Ruling(IArbitrator(msg.sender), _disputeID, uint256(resultRuling)); executeRuling(_disputeID, uint256(resultRuling)); } /** @dev Executes the ruling of a dispute. * @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 executeRuling(uint256 _disputeID, uint256 _ruling) internal { uint256 taskID = disputeIDtoTaskID[_disputeID]; Task storage task = tasks[taskID]; task.status = Status.Resolved; task.ruling = _ruling; uint256 amount; if (_ruling == uint256(Party.None)) { task.requester.send(task.requesterDeposit); // The value of sumDeposit is split among parties in this case. If the sum is uneven the value of 1 wei can be burnt. amount = task.sumDeposit / 2; task.parties[uint256(Party.Translator)].send(amount); task.parties[uint256(Party.Challenger)].send(amount); } else if (_ruling == uint256(Party.Translator)) { amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); } else { task.requester.send(task.requesterDeposit); task.parties[uint256(Party.Challenger)].send(task.sumDeposit); } task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(taskID, "dispute-settled", block.timestamp); } /** @dev Submit a reference to evidence. EVENT. * @param _taskID The ID of the task. * @param _evidence A link to evidence using its URI. */ function submitEvidence(uint256 _taskID, string calldata _evidence) external { Task storage task = tasks[_taskID]; require(task.status != Status.Resolved, "The task must not already be resolved."); emit Evidence(arbitrator, _taskID, msg.sender, _evidence); } // ******************** // // * Getters * // // ******************** // /** @dev Returns the sum of withdrawable wei from appeal rounds. This function is O(n), where n is the number of rounds of the task. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _taskID The ID of the associated task. * @param _beneficiary The contributor for which to query. * @return total The total amount of wei available to withdraw. */ function amountWithdrawable(uint256 _taskID, address payable _beneficiary) external view returns (uint256 total) { Task storage task = tasks[_taskID]; if (task.status != Status.Resolved) return total; for (uint256 i = 0; i < task.rounds.length; i++) { Round storage round = task.rounds[i]; if (!round.hasPaid[uint256(Party.Translator)] || !round.hasPaid[uint256(Party.Challenger)]) { total += round.contributions[_beneficiary][uint256(Party.Translator)] + round.contributions[_beneficiary][uint256(Party.Challenger)]; } else if (task.ruling == uint256(Party.None)) { uint256 rewardTranslator = round.paidFees[uint256(Party.Translator)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Translator)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; uint256 rewardChallenger = round.paidFees[uint256(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; total += rewardTranslator + rewardChallenger; } else { total += round.paidFees[uint256(task.ruling)] > 0 ? (round.contributions[_beneficiary][uint256(task.ruling)] * round.feeRewards) / round.paidFees[uint256(task.ruling)] : 0; } } return total; } /** @dev Gets the deposit required for self-assigning the task. * @param _taskID The ID of the task. * @return deposit The translator's deposit. */ function getDepositValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { deposit = NOT_PAYABLE_VALUE; } else { uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); deposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); } } /** @dev Gets the deposit required for challenging the translation. * @param _taskID The ID of the task. * @return deposit The challengers's deposit. */ function getChallengeValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > reviewTimeout || task.status != Status.AwaitingReview) { deposit = NOT_PAYABLE_VALUE; } else { uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); deposit = arbitrationCost.addCap((challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR); } } /** @dev Gets the current price of a specified task. * @param _taskID The ID of the task. * @return price The price of the task. */ function getTaskPrice(uint256 _taskID) public view returns (uint256 price) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { price = 0; } else { price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; } } /** @dev Gets the total number of created tasks. * @return The number of created tasks. */ function getTaskCount() public view returns (uint256) { return tasks.length; } /** @dev Gets the number of rounds of the specific task. * @param _taskID The ID of the task. * @return The number of rounds. */ function getNumberOfRounds(uint256 _taskID) public view returns (uint256) { Task storage task = tasks[_taskID]; return task.rounds.length; } /** @dev Gets the contributions made by a party for a given round of appeal of a task. * @param _taskID The ID of the task. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return contributions The contributions. */ function getContributions( uint256 _taskID, uint256 _round, address _contributor ) public view returns (uint256[3] memory contributions) { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; contributions = round.contributions[_contributor]; } /** @dev Gets the addresses of parties of a specified task. * @param _taskID The ID of the task. * @return parties The addresses of translator and challenger as [ZERO_ADDRESS, translator, challenger]. */ function getTaskParties(uint256 _taskID) public view returns (address payable[3] memory parties) { Task storage task = tasks[_taskID]; parties = task.parties; } /** @dev Gets the information on a round of a task. * @param _taskID The ID of the task. * @param _round The round to be queried. * @return paidFees The amount paid by each party in the round. * @return hasPaid Whether or not a given party has paid the full fees for the round. * @return feeRewards The amount of fees that will be available as rewards for the winner. */ function getRoundInfo(uint256 _taskID, uint256 _round) public view returns ( uint256[3] memory paidFees, bool[3] memory hasPaid, uint256 feeRewards ) { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; return (round.paidFees, round.hasPaid, round.feeRewards); } } 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } 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); } } contract ERC20Mock is ERC20, ERC20Burnable { constructor(address initialAccount, uint256 initialBalance) ERC20("MockToken", "MCT") { _mint(initialAccount, initialBalance); } }
0x60806040526004361061023b5760003560e01c806382b350171161012e578063b5f3918b116100ab578063cc7b9d061161006f578063cc7b9d0614610a77578063d2dbe1d814610aa2578063d661dd3114610acc578063e4c0aaf414610ae1578063fc6f8f1614610b145761023b565b8063b5f3918b14610984578063b8573185146109ae578063c17a340e146109cb578063c36cd196146109e0578063c4e690df14610a625761023b565b806395c95522116100f257806395c955221461085a578063a6a7f0eb14610884578063a95c980514610906578063aba4ab7414610930578063adc7faba1461095a5761023b565b806382b3501714610613578063881f7c571461068d5780638a9bb02a146107025780638d9776721461079d57806392239dff146108305761023b565b8063244772e8116101bc57806368c76ffd1161018057806368c76ffd146105095780636cc6cde1146105805780636e8218aa146105955780636e99a23a146105bf5780637b943383146105fe5761023b565b8063244772e814610440578063311a6c561461046a578063339ac67c1461049a5780633a2dabfa146104df57806341658341146104f45761023b565b806312b3a2c01161020357806312b3a2c01461039c57806312ce3525146103c25780631972483a146103ec5780631d5120851461041657806320c58ca51461042b5761023b565b8063064ba1891461024057806309e24ad41461027c5780630c340a24146102a85780630c7ac7b6146102d95780631165542b14610363575b600080fd5b34801561024c57600080fd5b5061026a6004803603602081101561026357600080fd5b5035610b3e565b60408051918252519081900360200190f35b34801561028857600080fd5b506102a66004803603602081101561029f57600080fd5b5035610b50565b005b3480156102b457600080fd5b506102bd610b9e565b604080516001600160a01b039092168252519081900360200190f35b3480156102e557600080fd5b506102ee610bad565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610328578181015183820152602001610310565b50505050905090810190601f1680156103555780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561036f57600080fd5b5061026a6004803603604081101561038657600080fd5b50803590602001356001600160a01b0316610c3a565b6102a6600480360360408110156103b257600080fd5b508035906020013560ff16610e4a565b3480156103ce57600080fd5b506102a6600480360360208110156103e557600080fd5b50356116fb565b3480156103f857600080fd5b5061026a6004803603602081101561040f57600080fd5b5035611749565b34801561042257600080fd5b5061026a6118e8565b34801561043757600080fd5b5061026a6118ee565b34801561044c57600080fd5b5061026a6004803603602081101561046357600080fd5b50356118f4565b34801561047657600080fd5b506102a66004803603604081101561048d57600080fd5b508035906020013561197b565b3480156104a657600080fd5b506102a6600480360360808110156104bd57600080fd5b506001600160a01b038135169060208101359060408101359060600135611b3e565b3480156104eb57600080fd5b5061026a611b97565b34801561050057600080fd5b5061026a611b9d565b34801561051557600080fd5b506105486004803603606081101561052c57600080fd5b50803590602081013590604001356001600160a01b0316611ba3565b6040518082606080838360005b8381101561056d578181015183820152602001610555565b5050505090500191505060405180910390f35b34801561058c57600080fd5b506102bd611c3f565b3480156105a157600080fd5b5061026a600480360360208110156105b857600080fd5b5035611c63565b3480156105cb57600080fd5b506102a6600480360360608110156105e257600080fd5b506001600160a01b038135169060208101359060400135611e1a565b34801561060a57600080fd5b5061026a6120cf565b61026a6004803603606081101561062957600080fd5b813591602081013591810190606081016040820135600160201b81111561064f57600080fd5b82018360208201111561066157600080fd5b803590602001918460018302840111600160201b8311171561068257600080fd5b5090925090506120d5565b6102a6600480360360408110156106a357600080fd5b81359190810190604081016020820135600160201b8111156106c457600080fd5b8201836020820111156106d657600080fd5b803590602001918460018302840111600160201b831117156106f757600080fd5b509092509050612302565b34801561070e57600080fd5b506107326004803603604081101561072557600080fd5b508035906020013561281c565b6040518084606080838360005b8381101561075757818101518382015260200161073f565b5050505090500183600360200280838360005b8381101561078257818101518382015260200161076a565b50505050905001828152602001935050505060405180910390f35b3480156107a957600080fd5b506107c7600480360360208110156107c057600080fd5b5035612917565b604051808b81526020018a81526020018981526020018860048111156107e957fe5b8152602001878152602001866001600160a01b031681526020018581526020018481526020018381526020018281526020019a505050505050505050505060405180910390f35b34801561083c57600080fd5b506102a66004803603602081101561085357600080fd5b5035612989565b34801561086657600080fd5b506105486004803603602081101561087d57600080fd5b50356129d7565b34801561089057600080fd5b506102a6600480360360408110156108a757600080fd5b81359190810190604081016020820135600160201b8111156108c857600080fd5b8201836020820111156108da57600080fd5b803590602001918460018302840111600160201b831117156108fb57600080fd5b509092509050612a43565b34801561091257600080fd5b506102a66004803603602081101561092957600080fd5b5035612b51565b34801561093c57600080fd5b506102a66004803603602081101561095357600080fd5b5035612b9f565b34801561096657600080fd5b506102a66004803603602081101561097d57600080fd5b5035612d0e565b34801561099057600080fd5b506102a6600480360360208110156109a757600080fd5b5035612d5c565b6102a6600480360360208110156109c457600080fd5b5035612daa565b3480156109d757600080fd5b5061026a6130db565b3480156109ec57600080fd5b506102a660048036036040811015610a0357600080fd5b81359190810190604081016020820135600160201b811115610a2457600080fd5b820183602082011115610a3657600080fd5b803590602001918460018302840111600160201b83111715610a5757600080fd5b5090925090506130e1565b348015610a6e57600080fd5b5061026a613286565b348015610a8357600080fd5b50610a8c61328c565b6040805160ff9092168252519081900360200190f35b348015610aae57600080fd5b506102a660048036036020811015610ac557600080fd5b5035613291565b348015610ad857600080fd5b5061026a613418565b348015610aed57600080fd5b506102a660048036036020811015610b0457600080fd5b50356001600160a01b031661341e565b348015610b2057600080fd5b5061026a60048036036020811015610b3757600080fd5b5035613489565b60096020526000908152604090205481565b6000546001600160a01b03163314610b995760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600255565b6000546001600160a01b031681565b60018054604080516020600284861615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610c325780601f10610c0757610100808354040283529160200191610c32565b820191906000526020600020905b815481529060010190602001808311610c1557829003601f168201915b505050505081565b60008060088481548110610c4a57fe5b60009182526020909120600e9091020190506004600382015460ff166004811115610c7157fe5b14610c7c5750610e44565b60005b600c820154811015610e4157600082600c018281548110610c9c57fe5b60009182526020909120600360069092020190810154909150610100900460ff161580610cd45750600381015462010000900460ff16155b15610d09576001600160a01b038516600090815260058201602052604090206002810154600190910154019390930192610e38565b600d830154610dc357600080826001015411610d26576000610d62565b8160020154826001015460048401546001600160a01b038916600090815260058601602052604090209290910191600101540281610d6057fe5b045b9050600080836002015411610d78576000610db4565b8260020154836001015460048501546001600160a01b038a16600090815260058701602052604090209290910191600201540281610db257fe5b045b91909101949094019350610e38565b60008160000184600d015460038110610dd857fe5b015411610de6576000610e33565b600d830154819060038110610df757fe5b015460048201546001600160a01b03871660009081526005840160205260409020600d86015460038110610e2757fe5b01540281610e3157fe5b045b840193505b50600101610c7f565b50505b92915050565b600060088381548110610e5957fe5b60009182526020909120600e9091020190506001826002811115610e7957fe5b1480610e9057506002826002811115610e8e57fe5b145b610ecb5760405162461bcd60e51b81526004018080602001828103825260368152602001806139ec6036913960400191505060405180910390fd5b60038082015460ff166004811115610edf57fe5b14610f29576040805162461bcd60e51b81526020600482015260156024820152742737903234b9b83aba32903a379030b83832b0b61760591b604482015290519081900360640190fd5b60017f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03166310f169e883600b01546040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b158015610f9357600080fd5b505afa158015610fa7573d6000803e3d6000fd5b505050506040513d6020811015610fbd57600080fd5b50516002811115610fca57fe5b1461101c576040805162461bcd60e51b815260206004820152601a60248201527f44697370757465206973206e6f742061707065616c61626c652e000000000000604482015290519081900360640190fd5b6000807f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b031663afe15cfb84600b01546040518263ffffffff1660e01b815260040180828152602001915050604080518083038186803b15801561108657600080fd5b505afa15801561109a573d6000803e3d6000fd5b505050506040513d60408110156110b057600080fd5b50805160209091015190925090504282118015906110cd57508042105b6111085760405162461bcd60e51b815260040180806020018281038252602e815260200180613744602e913960400191505060405180910390fd5b60007f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b0316631c3db16d85600b01546040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561117257600080fd5b505afa158015611186573d6000803e3d6000fd5b505050506040513d602081101561119c57600080fd5b5051905060008560028111156111ae57fe5b8214156111be5750600654611216565b816111cc5750600554611216565b600284840304844203106112115760405162461bcd60e51b815260040180806020018281038252603e815260200180613803603e913960400191505060405180910390fd5b506007545b600c8501805460009190600019810190811061122e57fe5b906000526020600020906006020190508060030187600281111561124e57fe5b6003811061125857fe5b602081049091015460ff601f9092166101000a900416156112aa5760405162461bcd60e51b81526004018080602001828103825260218152602001806139a66021913960400191505060405180910390fd5b600b8601546040805163791f8b7360e11b8152600481018381526024820192835260018054600260001961010083851615020190911604604484018190526000956001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe28069169563f23f16e695919492909160640190849080156113745780601f1061134957610100808354040283529160200191611374565b820191906000526020600020905b81548152906001019060200180831161135757829003601f168201915b5050935050505060206040518083038186803b15801561139357600080fd5b505afa1580156113a7573d6000803e3d6000fd5b505050506040513d60208110156113bd57600080fd5b5051905060006113e36127106113d384876134b4565b816113da57fe5b849190046134e8565b90506000806114143461140f878e60028111156113fc57fe5b6003811061140657fe5b015486906134fd565b613518565b3360009081526005880160205260409020919350915082908c600281111561143857fe5b6003811061144257fe5b018054909101905581858c600281111561145857fe5b6003811061146257fe5b018054909101905560405133908d907f22039e79a27860a038aece214124c8ecef12fdc1334feb8e8a157a0ae16a1db4908e908690808360028111156114a457fe5b81526020018281526020019250505060405180910390a382858c60028111156114c957fe5b600381106114d357fe5b015410611583576001856003018c60028111156114ec57fe5b600381106114f657fe5b602091828204019190066101000a81548160ff021916908315150217905550846000018b600281111561152557fe5b6003811061152f57fe5b015460048601805490910190556040518c907f213276d821d6205d87fa4f4658db4bf5a24a2323b0fdd8ffcd239c445f86a57b908d908082600281111561157257fe5b815260200191505060405180910390a25b604051339082156108fc029083906000818181858888f1505050506003860154610100900460ff16905080156115c35750600385015462010000900460ff165b156116ed57600b8a01546040805163093225f160e31b8152600481018381526024820192835260018054600260001961010083851615020190911604604484018190526001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe2806916956349912f88958b95919492909160640190849080156116915780601f1061166657610100808354040283529160200191611691565b820191906000526020600020905b81548152906001019060200180831161167457829003601f168201915b505093505050506000604051808303818588803b1580156116b157600080fd5b505af11580156116c5573d6000803e3d6000fd5b505050600c8c0180546001018155600052505060048501546116e790856134fd565b60048601555b505050505050505050505050565b6000546001600160a01b031633146117445760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600555565b6000806008838154811061175957fe5b90600052602060002090600e0201905060025481600401544203118061179257506002600382015460ff16600481111561178f57fe5b14155b156117a6576001600160ff1b0391506118e2565b60405163f7434ea960e01b815260206004820190815260018054600260001961010083851615020190911604602484018190526000936001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe28069169363f7434ea9939290918291604490910190849080156118675780601f1061183c57610100808354040283529160200191611867565b820191906000526020600020905b81548152906001019060200180831161184a57829003601f168201915b50509250505060206040518083038186803b15801561188557600080fd5b505afa158015611899573d6000803e3d6000fd5b505050506040513d60208110156118af57600080fd5b505160068301546004549192506118de91612710916118ce91906134b4565b816118d557fe5b839190046134e8565b9250505b50919050565b60075481565b60045481565b6000806008838154811061190457fe5b90600052602060002090600e02019050806000015481600401544203118061193f57506000600382015460ff16600481111561193c57fe5b14155b1561194d57600091506118e2565b8060000154816004015442038260010154836002015403028161196c57fe5b04816001015401915050919050565b600081600281111561198957fe5b600084815260096020526040812054600880549394509092839081106119ab57fe5b600091825260208220600c600e9092020190810180549193509060001981019081106119d357fe5b906000526020600020906006020190507f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b0316336001600160a01b031614611a535760405162461bcd60e51b81526004018080602001828103825260218152602001806137e26021913960400191505060405180910390fd5b60038083015460ff166004811115611a6757fe5b14611aa35760405162461bcd60e51b81526004018080602001828103825260268152602001806137726026913960400191505060405180910390fd5b600381015460ff61010090910416151560011415611ac45760019350611ae1565b600381015462010000900460ff16151560011415611ae157600293505b85337f394027a5fa6e098a1191094d1719d6929b9abc535fcc0c8f448d6a4e75622276866002811115611b1057fe5b60408051918252519081900360200190a3611b3686856002811115611b3157fe5b61353d565b505050505050565b600060088481548110611b4d57fe5b90600052602060002090600e0201905060008390505b600c82015481108015611b7f5750821580611b7f575082840181105b15611b3657611b8f868683611e1a565b600101611b63565b60035481565b60055481565b611bab613725565b600060088581548110611bba57fe5b90600052602060002090600e02019050600081600c018581548110611bdb57fe5b600091825260208083206001600160a01b03881684526005600690930201918201905260409182902082516060810190935290925060038282826020028201915b815481526020019060010190808311611c1c575050505050925050509392505050565b7f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe2806981565b60008060088381548110611c7357fe5b90600052602060002090600e020190508060000154816004015442031180611cae57506000600382015460ff166004811115611cab57fe5b14155b15611cc2576001600160ff1b0391506118e2565b600081600001548260040154420383600101548460020154030281611ce357fe5b60018481015460405163f7434ea960e01b81526020600482019081528354600281861615610100026000190190911604602483018190529590940490910194506000937f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03169363f7434ea99392909182916044019084908015611daf5780601f10611d8457610100808354040283529160200191611daf565b820191906000526020600020905b815481529060010190602001808311611d9257829003601f168201915b50509250505060206040518083038186803b158015611dcd57600080fd5b505afa158015611de1573d6000803e3d6000fd5b505050506040513d6020811015611df757600080fd5b5051600354909150611e1190612710906118ce90856134b4565b95945050505050565b600060088381548110611e2957fe5b90600052602060002090600e02019050600081600c018381548110611e4a57fe5b6000918252602090912060069091020190506004600383015460ff166004811115611e7157fe5b14611ec3576040805162461bcd60e51b815260206004820152601c60248201527f546865207461736b2073686f756c64206265207265736f6c7665642e00000000604482015290519081900360640190fd5b6003810154600090610100900460ff161580611eea5750600382015462010000900460ff16155b15611f2457506001600160a01b038516600090815260058201602052604081206002810180546001909201805490849055929055016120a2565b600d83015461200157600080836001015411611f41576000611f7d565b8260020154836001015460048501546001600160a01b038a16600090815260058701602052604090209290910191600101540281611f7b57fe5b045b9050600080846002015411611f93576000611fcf565b8360020154846001015460048601546001600160a01b038b16600090815260058801602052604090209290910191600201540281611fcd57fe5b045b6001600160a01b0389166000908152600586016020526040812060018101829055600201559190910191506120a29050565b60008260000184600d01546003811061201657fe5b015411612024576000612071565b600d83015482906003811061203557fe5b015460048301546001600160a01b03881660009081526005850160205260409020600d8601546003811061206557fe5b0154028161206f57fe5b045b6001600160a01b03871660009081526005840160205260408120600d86015492935090916003811061209f57fe5b01555b6040516001600160a01b0387169082156108fc029083906000818181858888f15050505050505050505050565b60065481565b6000833410156121165760405162461bcd60e51b8152600401808060200182810382526041815260200180613a486041913960600191505060405180910390fd5b4285116121545760405162461bcd60e51b81526004018080602001828103825260258152602001806139c76025913960400191505060405180910390fd5b506008805460018101825560009190915242808603600e83027ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee381019182557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee48101879055347ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee582018190557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee78201939093557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee8810180546001600160a01b031916331790557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee90191909155604080516020808252810185905283917f61606860eb6c87306811e2695215385101daab53bd6ab4e9f9049aead9363c7d91879187919081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2604080514281529051339184917f6cf53aa7292e664152c2ea948c3b3c95d4b05c36daeb2626d0293473c4a4a1539181900360200190a350949350505050565b60006008848154811061231157fe5b6000918252602080832060405163f7434ea960e01b8152600481019283526001805460026000196101008385161502019091160460248301819052600e90950290920195506001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe28069169363f7434ea993918291604490910190849080156123df5780601f106123b4576101008083540402835291602001916123df565b820191906000526020600020905b8154815290600101906020018083116123c257829003601f168201915b50509250505060206040518083038186803b1580156123fd57600080fd5b505afa158015612411573d6000803e3d6000fd5b505050506040513d602081101561242757600080fd5b5051600683015460045491925060009161244891612710916113d3916134b4565b90506002600384015460ff16600481111561245f57fe5b146124b1576040805162461bcd60e51b815260206004820181905260248201527f546865207461736b20697320696e207468652077726f6e67207374617475732e604482015290519081900360640190fd5b6002548360040154420311156124f85760405162461bcd60e51b81526004018080602001828103825260248152602001806139826024913960400191505060405180910390fd5b803410156125375760405162461bcd60e51b815260040180806020018281038252602a815260200180613864602a913960400191505060405180910390fd5b6003838101805460ff19169091179055600a830180546001600160a01b031916331790556040805163c13517e160e01b8152600260048201818152602483019384526001805460001981831615610100020116839004604485018190527f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03169563c13517e195899594926064909101908490801561261e5780601f106125f35761010080835404028352916020019161261e565b820191906000526020600020905b81548152906001019060200180831161260157829003601f168201915b505093505050506020604051808303818588803b15801561263e57600080fd5b505af1158015612652573d6000803e3d6000fd5b50505050506040513d602081101561266957600080fd5b5051600b84018190556000908152600960205260408120879055600c840180546001018155905260078301546126ab9083906126a590846134e8565b906134fd565b60078401556040513482900390339082156108fc029083906000818181858888f193505050505083600b01547f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03167f74baab670a4015ab2f1b467c5252a96141a2573f2908e58a92081e80d3cfde3d898a604051808381526020018281526020019250505060405180910390a3604080514281529051339189917f6f0bb1c54bb0ad8822894f45a3837ab62e23e77d25c5881ab57e1c6a99f7e0b59181900360200190a3841561281357336001600160a01b0316877f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03167fdccf2f8b2cc26eafcd61905cba744cff4b81d14740725f6376390dc6298a6a3c898960405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a45b50505050505050565b612824613725565b61282c613725565b6000806008868154811061283c57fe5b90600052602060002090600e02019050600081600c01868154811061285d57fe5b9060005260206000209060060201905080600001816003018260040154826003806020026040519081016040528092919082600380156128b2576020028201915b81548152602001906001019080831161289e575b5050604080516060810191829052949750869350600392509050826000855b825461010083900a900460ff1615158152602060019283018181049485019490930390920291018084116128d15790505050505050915094509450945050509250925092565b6008818154811061292757600080fd5b60009182526020909120600e9091020180546001820154600283015460038401546004850154600586015460068701546007880154600b890154600d909901549799509597949660ff9094169592946001600160a01b0390921693909291908a565b6000546001600160a01b031633146129d25760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600755565b6129df613725565b6000600883815481106129ee57fe5b60009182526020909120604080516060810191829052600e9093029091019250600883019060039082845b81546001600160a01b03168152600190910190602001808311612a19575050505050915050919050565b600060088481548110612a5257fe5b60009182526020909120600e9091020190506004600382015460ff166004811115612a7957fe5b1415612ab65760405162461bcd60e51b8152600401808060200182810382526026815260200180613a226026913960400191505060405180910390fd5b336001600160a01b0316847f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03167fdccf2f8b2cc26eafcd61905cba744cff4b81d14740725f6376390dc6298a6a3c868660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a450505050565b6000546001600160a01b03163314612b9a5760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600355565b600060088281548110612bae57fe5b60009182526020909120600e9091020190506002600382015460ff166004811115612bd557fe5b10612c115760405162461bcd60e51b815260040180806020018281038252602d815260200180613955602d913960400191505060405180910390fd5b80546004820154420311612c565760405162461bcd60e51b81526004018080602001828103825260328152602001806138f66032913960400191505060405180910390fd5b60038101805460ff1916600417905560078101546006820154600583015460405191909201916001600160a01b0316906108fc8315029083906000818181858888f150506000600686018190556007860155505060408051426020820152818152601481830152731c995c5d595cdd195c8b5c995a5b589d5c9cd95960621b606082015290518592507f5850eca3b971056e7a311e04b06c359c0aceec8e422e4e015301e136efbd888a9181900360800190a2505050565b6000546001600160a01b03163314612d575760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600655565b6000546001600160a01b03163314612da55760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600455565b600060088281548110612db957fe5b90600052602060002090600e020190508060000154816004015442031115612e28576040805162461bcd60e51b815260206004820181905260248201527f54686520646561646c696e652068617320616c7265616479207061737365642e604482015290519081900360640190fd5b600081600001548260040154420383600101548460020154030281612e4957fe5b60018481015460405163f7434ea960e01b81526020600482019081528354600281861615610100026000190190911604602483018190529590940490910194506000937f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03169363f7434ea99392909182916044019084908015612f155780601f10612eea57610100808354040283529160200191612f15565b820191906000526020600020905b815481529060010190602001808311612ef857829003601f168201915b50509250505060206040518083038186803b158015612f3357600080fd5b505afa158015612f47573d6000803e3d6000fd5b505050506040513d6020811015612f5d57600080fd5b5051600354909150600090612f7a90612710906113d390866134b4565b90506000600385015460ff166004811115612f9157fe5b14612fcd5760405162461bcd60e51b815260040180806020018281038252602d815260200180613928602d913960400191505060405180910390fd5b8034101561300c5760405162461bcd60e51b8152600401808060200182810382526033815260200180613a896033913960400191505060405180910390fd5b6009840180546001600160a01b0319163317905560038401805460ff191660011790556002840154600585015460405191859003916001600160a01b0391909116906108fc8315029083906000818181858888f150505050600686018590555050600784018190556040513482900390339082156108fc029083906000818181858888f150506040805188815242602082015281513395508b94507f9c8de00bfaaca6ca425ca3047c87c81f398e79f7c15166f53dcb29782ef9da4293509081900390910190a3505050505050565b60085490565b6000600884815481106130f057fe5b60009182526020909120600e9091020190506001600382015460ff16600481111561311757fe5b146131535760405162461bcd60e51b815260040180806020018281038252604a815260200180613798604a913960600191505060405180910390fd5b80546004820154420311156131af576040805162461bcd60e51b815260206004820181905260248201527f54686520646561646c696e652068617320616c7265616479207061737365642e604482015290519081900360640190fd5b60088101600101546001600160a01b031633146131fd5760405162461bcd60e51b815260040180806020018281038252603f8152602001806138b7603f913960400191505060405180910390fd5b60038101805460ff1916600217905542600482018190556040805160208101839052818152908101849052339186917f81c1cc8daea412565717a44fb42a08dbcb5d73101f5473d062391293c947d26d9187918791908060608101858580828437600083820152604051601f909101601f1916909201829003965090945050505050a350505050565b60025481565b600081565b6000600882815481106132a057fe5b60009182526020909120600e9091020190506002600382015460ff1660048111156132c757fe5b14613319576040805162461bcd60e51b815260206004820181905260248201527f546865207461736b20697320696e207468652077726f6e67207374617475732e604482015290519081900360640190fd5b600254816004015442031161335f5760405162461bcd60e51b81526004018080602001828103825260238152602001806138416023913960400191505060405180910390fd5b60038101805460ff19166004179055600781015460068201540160088201600101546040516001600160a01b039091169082156108fc029083906000818181858888f150506000600686018190556007860155505060408051426020820152818152601481830152731d1c985b9cdb185d1a5bdb8b5858d8d95c1d195960621b606082015290518592507f5850eca3b971056e7a311e04b06c359c0aceec8e422e4e015301e136efbd888a9181900360800190a2505050565b61271081565b6000546001600160a01b031633146134675760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000806008838154811061349957fe5b60009182526020909120600e90910201600c01549392505050565b6000826134c357506000610e44565b828202828482816134d057fe5b04146134de576000196134e0565b805b949350505050565b6000828201838110156134de576000196134e0565b60008282111561350f57506000610e44565b50808203610e44565b6000808383111561352e57508290506000613536565b508190508083035b9250929050565b600082815260096020526040812054600880549192918390811061355d57fe5b6000918252602082206003600e90920201908101805460ff19166004179055600d810185905591508361363857600582015460068301546040516001600160a01b039092169181156108fc0291906000818181858888f193505050505060028260070154816135c857fe5b60098401546040519290910492506001600160a01b0316906108fc8315029083906000818181858888f1505050600884019150600290505b6003811061360a57fe5b01546040516001600160a01b039091169082156108fc029083906000818181858888f19350505050506136b6565b600184141561365857506007810154600682015401600882016001613600565b600582015460068301546040516001600160a01b039092169181156108fc0291906000818181858888f150505050600a83015460078401546040516001600160a01b03909216925080156108fc02916000818181858888f150505050505b600060068301819055600783015560408051426020820152818152600f818301526e191a5cdc1d5d194b5cd95d1d1b1959608a1b6060820152905184917f5850eca3b971056e7a311e04b06c359c0aceec8e422e4e015301e136efbd888a919081900360800190a25050505050565b6040518060600160405280600390602082028036833750919291505056fe46756e64696e67206d757374206265206d6164652077697468696e207468652061707065616c20706572696f642e54686520646973707574652068617320616c7265616479206265656e207265736f6c7665642e546865207461736b20697320656974686572206e6f742061737369676e6564206f72207472616e736c6174696f6e2068617320616c7265616479206265656e207375626d69747465642e4d7573742062652063616c6c6564206279207468652061726269747261746f722e546865206c6f736572206d7573742070617920647572696e67207468652066697273742068616c66206f66207468652061707065616c20706572696f642e54686520726576696577207068617365206861736e277420706173736564207965742e4e6f7420656e6f7567682045544820746f20636f766572206368616c6c656e6765206465706f7369742e4f6e6c7920676f7665726e6f7220697320616c6c6f77656420746f20706572666f726d20746869732e43616e2774207375626d6974207472616e736c6174696f6e20746f2061207461736b2074686174207761736e27742061737369676e656420746f20796f752e43616e2774207265696d62757273652069662074686520646561646c696e65206861736e277420706173736564207965742e5461736b2068617320616c7265616479206265656e2061737369676e6564206f72207265696d6275727365642e43616e2774207265696d6275727365206966207472616e736c6174696f6e20776173207375626d69747465642e546865207265766965772070686173652068617320616c7265616479207061737365642e41707065616c206665652068617320616c7265616479206265656e20706169642e54686520646561646c696e652073686f756c6420626520696e20746865206675747572652e526563697069656e74206d7573742062652065697468657220746865207472616e736c61746f72206f72206368616c6c656e6765722e546865207461736b206d757374206e6f7420616c7265616479206265207265736f6c7665642e4465706f73697465642076616c75652073686f756c642062652067726561746572207468616e206f7220657175616c20746f20746865206d696e2070726963652e4e6f7420656e6f7567682045544820746f20726561636820746865207265717569726564206465706f7369742076616c75652ea26469706673582212203515ad57a5cb9f5e12f5aee09364ffc2498a2b8ccab69895db70f2fb17d0fbea64736f6c63430007040033
[ 13, 25, 11 ]
0x4486bec9e151d7fcd0f0bf2fa21a4236fa4da13b
pragma solidity 0.6.6; 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"); 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); } } } } 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract GromToken is ERC20 { constructor () public ERC20("GROM", "GR") { _setupDecimals(6); _mint(msg.sender, 100000000 * (10 ** uint256(decimals()))); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b6106778560405180606001604052806028815260200161102660289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161109760259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110736024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fde6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061104e6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fbb6023913960400191505060405180910390fd5b610cc3838383610fb5565b610d2e81604051806060016040528060268152602001611000602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610dc1816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f1a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610edf578082015181840152602081019050610ec4565b50505050905090810190601f168015610f0c5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fab576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa26469706673582212202372eccf714fae1f6e9c7946f55704f7cbcf793d766c91f183ba52c3a924a5e664736f6c63430006060033
[ 38 ]
0x450D6644B994F984DDB8eb194015b70eE2626258
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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"); } } library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } 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)); } } library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - (subtracted.a), p); } else { difference.a = p - (addmod(subtracted.a, p - (diminished.a), p)); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - (subtracted.b), p); } else { difference.b = p - (addmod(subtracted.b, p - (diminished.b), p)); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = p - addmod(t2, p - t0, p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = p - mulmod(value.b, t3, p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG1() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = p - sum.y.a; sum.y.b = p - sum.y.b; } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = p - result.y.a; result.y.b = p - result.y.b; } } } library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } 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; } library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint newValue = sequence.value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value != newValue) { sequence.value = newValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint _i = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len.sub(1); while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getTokenLaunchLocker() external view returns (address) { return getContract(TOKEN_LAUNCH_LOCKER); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Returns the number of Nodes and resource divisor that is needed for a * given Schain type. */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { revert("Bad schain type"); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainId = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainId); } function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId]; } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); } else { schainsForNodes[nodeIndex][holesForNodes[nodeIndex][0]] = schainId; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForNodes[nodeIndex].length; i++) { if (min > holesForNodes[nodeIndex][i]) { min = holesForNodes[nodeIndex][i]; index = i; } } if (min == uint(-1)) { delete holesForNodes[nodeIndex]; } else { holesForNodes[nodeIndex][0] = min; holesForNodes[nodeIndex][index] = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; holesForNodes[nodeIndex].pop(); } } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) public view returns (uint) { return schainsForNodes[nodeIndex].length; } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { uint length = getLengthOfSchainsForNode(nodeIndex); for (uint i = 0; i < length; i++) { if (schainsForNodes[nodeIndex][i] == schainId) { return i; } } return length; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } /** * @dev Swaps one index for another in an array. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); event BountyGot( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce}); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); bool completed; bool isSchains = false; if (schainsInternal.getActiveSchain(nodeIndex) != bytes32(0)) { completed = nodeRotation.exitFromSchain(nodeIndex); isSchains = true; } else { completed = true; } if (completed) { require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime(nodeIndex, now.add(isSchains ? constants.rotationDelay() : 0)); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.removeCheckedNodes(nodeIndex); // monitors.deleteMonitor(nodeIndex); nodes.deleteNodeForValidator(validatorId, nodeIndex); } } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require( nodes.isNodeActive(nodeIndex) || nodes.isNodeLeaving(nodeIndex), "Node is not Active and is not Leaving" ); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); if (bounty > 0) { _payBounty(bounty, nodes.getValidatorId(nodeIndex)); } _emitBountyEvent(nodeIndex, msg.sender, 0, 0, bounty); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _emitBountyEvent( uint nodeIndex, address from, uint averageDowntime, uint averageLatency, uint bounty ) private { Monitors monitors = Monitors(contractManager.getContract("Monitors")); uint previousBlockEvent = monitors.getLastBountyBlock(nodeIndex); monitors.setLastBountyBlock(nodeIndex); emit BountyReceived( nodeIndex, from, averageDowntime, averageLatency, bounty, previousBlockEvent, block.timestamp, gasleft()); emit BountyGot( nodeIndex, from, averageDowntime, averageLatency, bounty, previousBlockEvent, block.timestamp, gasleft()); } } contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB; if (!(signature.a == 0 && signature.b == 0)) { newSignB = Fp2Operations.P.sub((signature.b % Fp2Operations.P)); } else { newSignB = signature.b; } require(G2Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G2Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; /** * @dev Allows TokenLaunchManager contract to lock an amount of tokens in a * holder wallet. * * Emits a {Locked} event. */ function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new delegations. */ function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new undelegation requests. */ function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev Returns and updates the current delegated amount. */ function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } /** * @dev Adds a delegated amount to the given month. */ function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } /** * @dev Removes a delegated amount from the given month. */ function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } /** * @dev Adds the amount to the total delegated for the given month. */ function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Cannot add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } /** * @dev Unlocks tokens. * * Emits an {Unlocked} event. */ function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } /** * @dev Deletes the delegated amount. */ function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } /** * @dev Deletes the total delegated amount. */ function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } /** * @dev Checks whether total delegated satisfies Proof-of-Use. */ function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } contract TokenState is Permissions, ILocker { string[] private _lockers; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint locked = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); uint bounty = _calculateMaximumBountyAmount(_epochPool, currentMonth, nodeIndex, constantsHolder, nodes); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint validatorId, uint amount, uint month ) external allow("DelegationController") { if (nodesByValidator[validatorId] > 0) { _effectiveDelegatedSum.addToValue(amount.mul(nodesByValidator[validatorId]), month); } } function handleDelegationRemoving( uint validatorId, uint amount, uint month ) external allow("DelegationController") { if (nodesByValidator[validatorId] > 0) { _effectiveDelegatedSum.subtractFromValue(amount.mul(nodesByValidator[validatorId]), month); } } function handleNodeCreation(uint validatorId) external allow("Nodes") { nodesByValidator[validatorId] = nodesByValidator[validatorId].add(1); _changeEffectiveDelegatedSum(validatorId, true); } function handleNodeRemoving(uint validatorId) external allow("Nodes") { require(nodesByValidator[validatorId] > 0, "All nodes have been already removed"); nodesByValidator[validatorId] = nodesByValidator[validatorId].sub(1); _changeEffectiveDelegatedSum(validatorId, false); } function estimateBounty(uint /* nodeIndex */) external pure returns (uint) { revert("Not implemented"); // ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); // uint stagePoolSize; // uint nextStage; // (stagePoolSize, nextStage) = _getEpochPool(timeHelpers.getCurrentMonth(), timeHelpers, constantsHolder); // return _calculateMaximumBountyAmount( // stagePoolSize, // nextStage.sub(1), // nodeIndex, // constantsHolder, // nodes // ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint currentMonth, uint nodeIndex, ConstantsHolder constantsHolder, Nodes nodes ) private returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } uint effectiveDelegatedSum = _effectiveDelegatedSum.getAndUpdateValue(currentMonth); if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController")); return epochPoolSize .add(_bountyWasPaidInCurrentEpoch) .mul( delegationController.getAndUpdateEffectiveDelegatedToValidator( nodes.getValidatorId(nodeIndex), currentMonth ) ) .div(effectiveDelegatedSum); } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _changeEffectiveDelegatedSum(uint validatorId, bool add) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController")); uint currentMonth = timeHelpers.getCurrentMonth(); uint current = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(current == effectiveDelegated[0]); uint addedToStatistic = 0; bool addToCurrentMonth = now < timeHelpers.monthToTimestamp(currentMonth).add(nodeCreationWindowSeconds); for (uint i = 0; i < _max(effectiveDelegated.length, 2); ++i) { if (i > 0 || addToCurrentMonth) { uint _effectiveDelegated; if (i < effectiveDelegated.length) { _effectiveDelegated = effectiveDelegated[i]; } else { _effectiveDelegated = effectiveDelegated[effectiveDelegated.length.sub(1)]; } if (_effectiveDelegated != addedToStatistic) { _addToEffectiveDelegatedSum(currentMonth.add(i), _effectiveDelegated, addedToStatistic, add); addedToStatistic = _effectiveDelegated; } } } } } function _addToEffectiveDelegatedSum(uint month, uint newValue, uint oldValue, bool add) private { if (newValue > oldValue) { uint diff = newValue.sub(oldValue); if (add) { _effectiveDelegatedSum.addToValue(diff, month); } else { _effectiveDelegatedSum.subtractFromValue(diff, month); } } else if (newValue < oldValue) { uint diff = oldValue.sub(newValue); if (add) { _effectiveDelegatedSum.subtractFromValue(diff, month); } else { _effectiveDelegatedSum.addToValue(diff, month); } } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/8 of Node) uint8 public constant MEDIUM_DIVISOR = 8; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; _getTokenLaunchLocker().handleDelegationAdd( delegations[delegationId].holder, delegationId, amount, delegations[delegationId].started ); uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getTokenLaunchLocker().handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( validatorId, initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( validatorId, initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function getAndUpdateDelegatedToValidator(uint validatorId, uint month) public allow("Nodes") returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); require( _lockedInPendingDelegations[holder].month == currentMonth, "There are no delegation requests this month"); require(_lockedInPendingDelegations[holder].amount >= amount, "Unlocking amount is too big"); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) { return TokenLaunchLocker(contractManager.getTokenLaunchLocker()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } } contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } contract Monitors is Permissions { using StringUtils for string; using SafeCast for uint; struct Verdict { uint toNodeIndex; uint32 downtime; uint32 latency; } struct CheckedNode { uint nodeIndex; uint time; } struct CheckedNodeWithIp { uint nodeIndex; uint time; bytes4 ip; } mapping (bytes32 => CheckedNode[]) public checkedNodes; mapping (bytes32 => uint[][]) public verdicts; mapping (bytes32 => uint[]) public groupsForMonitors; mapping (bytes32 => uint) public lastVerdictBlocks; mapping (bytes32 => uint) public lastBountyBlocks; /** * @dev Emitted when a monitor group is created. */ event MonitorCreated( uint nodeIndex, bytes32 monitorIndex, uint numberOfMonitors, uint[] nodesInGroup, uint time, uint gasSpend ); /** * @dev Emitted when a verdict is sent. */ event VerdictSent( uint indexed fromMonitorIndex, uint indexed toNodeIndex, uint32 downtime, uint32 latency, bool status, uint previousBlockEvent, uint time, uint gasSpend ); /** * @dev Emitted when metrics are calculated. */ event MetricsCalculated( uint forNodeIndex, uint32 averageDowntime, uint32 averageLatency, uint time, uint gasSpend ); /** * @dev Emitted when monitoring periods are set. */ event PeriodsSet( uint rewardPeriod, uint deltaPeriod, uint time, uint gasSpend ); /** * @dev Emitted when node rotation in a monitor group is performed. */ event MonitorRotated( bytes32 monitorIndex, uint newNode ); /** * @dev Allows SkaleManager contract to create a monitoring group. * * Emits a {MonitorCreated} event. */ function addMonitor(uint nodeIndex) external allow("SkaleManager") { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); _generateGroup(monitorIndex, nodeIndex, constantsHolder.NUMBER_OF_MONITORS()); CheckedNode memory checkedNode = _getCheckedNodeData(nodeIndex); for (uint i = 0; i < groupsForMonitors[monitorIndex].length; i++) { bytes32 index = keccak256(abi.encodePacked(groupsForMonitors[monitorIndex][i])); addCheckedNode(index, checkedNode); } emit MonitorCreated( nodeIndex, monitorIndex, groupsForMonitors[monitorIndex].length, groupsForMonitors[monitorIndex], block.timestamp, gasleft() ); } /** * @dev Allows SkaleManager contract to delete a monitoring group. */ function deleteMonitor(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); while (verdicts[keccak256(abi.encodePacked(nodeIndex))].length > 0) { verdicts[keccak256(abi.encodePacked(nodeIndex))].pop(); } uint[] memory nodesInGroup = groupsForMonitors[monitorIndex]; uint index; bytes32 monitoringIndex; for (uint i = 0; i < nodesInGroup.length; i++) { monitoringIndex = keccak256(abi.encodePacked(nodesInGroup[i])); (index, ) = _find(monitoringIndex, nodeIndex); if (index < checkedNodes[monitoringIndex].length) { if (index != checkedNodes[monitoringIndex].length.sub(1)) { checkedNodes[monitoringIndex][index] = checkedNodes[monitoringIndex][checkedNodes[monitoringIndex].length.sub(1)]; } checkedNodes[monitoringIndex].pop(); } } delete groupsForMonitors[monitorIndex]; } /** * @dev Allows SkaleManager contract to remove nodes from a monitoring list. */ function removeCheckedNodes(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); delete checkedNodes[monitorIndex]; } /** * @dev Allows SkaleManager contract to send a monitoring verdict. * * Emits a {VerdictSent} event. * * Requirements: * * - Node must exist in the monitor group. */ function sendVerdict(uint fromMonitorIndex, Verdict calldata verdict) external allow("SkaleManager") { uint index; uint time; bytes32 monitorIndex = keccak256(abi.encodePacked(fromMonitorIndex)); (index, time) = _find(monitorIndex, verdict.toNodeIndex); require(time > 0, "Checked Node does not exist in MonitorsArray"); if (time <= block.timestamp) { if (index != checkedNodes[monitorIndex].length.sub(1)) { checkedNodes[monitorIndex][index] = checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; } delete checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; checkedNodes[monitorIndex].pop(); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bool receiveVerdict = time.add(constantsHolder.deltaPeriod()) > block.timestamp; if (receiveVerdict) { verdicts[keccak256(abi.encodePacked(verdict.toNodeIndex))].push( [uint(verdict.downtime), uint(verdict.latency)] ); } _emitVerdictsEvent(fromMonitorIndex, verdict, receiveVerdict); } } /** * @dev Allows SkaleManager contract to calculate median statistics of downtime * and latency. */ function calculateMetrics(uint nodeIndex) external allow("SkaleManager") returns (uint averageDowntime, uint averageLatency) { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); uint lengthOfArray = getLengthOfMetrics(monitorIndex); uint[] memory downtimeArray = new uint[](lengthOfArray); uint[] memory latencyArray = new uint[](lengthOfArray); for (uint i = 0; i < lengthOfArray; i++) { downtimeArray[i] = verdicts[monitorIndex][i][0]; latencyArray[i] = verdicts[monitorIndex][i][1]; } if (lengthOfArray > 0) { averageDowntime = _median(downtimeArray); averageLatency = _median(latencyArray); } delete verdicts[monitorIndex]; } /** * @dev Allows SkaleManager contract to set a node's last bounty block. */ function setLastBountyBlock(uint nodeIndex) external allow("SkaleManager") { lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))] = block.number; } /** * @dev Returns node info of nodes in a monitoring list. * Node info includes IPs, nodeIndex, and time to send verdict. * */ function getCheckedArray(bytes32 monitorIndex) external view returns (CheckedNodeWithIp[] memory checkedNodesWithIp) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNodesWithIp = new CheckedNodeWithIp[](checkedNodes[monitorIndex].length); for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { checkedNodesWithIp[i].nodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodesWithIp[i].time = checkedNodes[monitorIndex][i].time; checkedNodesWithIp[i].ip = nodes.getNodeIP(checkedNodes[monitorIndex][i].nodeIndex); } } /** * @dev Returns the latest blocknumber when node received bounty. */ function getLastBountyBlock(uint nodeIndex) external view returns (uint) { return lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))]; } /** * @dev Returns the nodes in a monitoring group. */ function getNodesInGroup(bytes32 monitorIndex) external view returns (uint[] memory) { return groupsForMonitors[monitorIndex]; } /** * @dev Returns the number of nodes in a monitoring group. */ function getNumberOfNodesInGroup(bytes32 monitorIndex) external view returns (uint) { return groupsForMonitors[monitorIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleManager contract to add checked node or update existing * one if it is already exits. */ function addCheckedNode(bytes32 monitorIndex, CheckedNode memory checkedNode) public allow("SkaleManager") { for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { if (checkedNodes[monitorIndex][i].nodeIndex == checkedNode.nodeIndex) { checkedNodes[monitorIndex][i] = checkedNode; return; } } checkedNodes[monitorIndex].push(checkedNode); } /** * @dev Returns the blocknumber when a node received its latest verdict. */ function getLastReceivedVerdictBlock(uint nodeIndex) public view returns (uint) { return lastVerdictBlocks[keccak256(abi.encodePacked(nodeIndex))]; } /** * @dev Returns a count of metric data available for a node. */ function getLengthOfMetrics(bytes32 monitorIndex) public view returns (uint) { return verdicts[monitorIndex].length; } /** * @dev Generates a monitoring group, using a pseudo-random number generator. */ function _generateGroup(bytes32 monitorIndex, uint nodeIndex, uint numberOfNodes) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint[] memory activeNodes = nodes.getActiveNodeIds(); uint numberOfNodesInGroup; uint availableAmount = activeNodes.length.sub((nodes.isNodeActive(nodeIndex)) ? 1 : 0); if (numberOfNodes > availableAmount) { numberOfNodesInGroup = availableAmount; } else { numberOfNodesInGroup = numberOfNodes; } uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), monitorIndex))); for (uint i = 0; i < numberOfNodesInGroup; ++i) { uint index = random % (activeNodes.length.sub(ignoringTail)); if (activeNodes[index] == nodeIndex) { _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; index = random % (activeNodes.length.sub(ignoringTail)); } groupsForMonitors[monitorIndex].push(activeNodes[index]); _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; } } /** * @dev Returns the median using the Quicksort algorithm. */ function _median(uint[] memory values) private pure returns (uint) { require(values.length > 0, "Cannot calculate _median of an empty array"); _quickSort(values, 0, values.length.sub(1)); return values[values.length.div(2)]; } /** * @dev Performs swap functions for monitoring group generation. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Performs find functions for monitoring indexes. */ function _find(bytes32 monitorIndex, uint nodeIndex) private view returns (uint index, uint time) { index = checkedNodes[monitorIndex].length; time = 0; for (uint i = 0; i < checkedNodes[monitorIndex].length; i++) { uint checkedNodeNodeIndex; uint checkedNodeTime; checkedNodeNodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodeTime = checkedNodes[monitorIndex][i].time; if (checkedNodeNodeIndex == nodeIndex && (time == 0 || checkedNodeTime < time)) { index = i; time = checkedNodeTime; } } } /** * @dev Performs Quicksort. */ function _quickSort(uint[] memory array, uint left, uint right) private pure { uint leftIndex = left; uint rightIndex = right; uint middle = array[right.add(left).div(2)]; while (leftIndex <= rightIndex) { while (array[leftIndex] < middle) { leftIndex++; } while (middle < array[rightIndex]) { rightIndex--; } if (leftIndex <= rightIndex) { (array[leftIndex], array[rightIndex]) = (array[rightIndex], array[leftIndex]); leftIndex++; rightIndex = (rightIndex > 0 ? rightIndex.sub(1) : 0); } } if (left < rightIndex) _quickSort(array, left, rightIndex); if (leftIndex < right) _quickSort(array, leftIndex, right); } /** * @dev Returns monitoring data for a node. */ function _getCheckedNodeData(uint nodeIndex) private view returns (CheckedNode memory checkedNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNode.nodeIndex = nodeIndex; checkedNode.time = nodes.getNodeLastRewardDate(nodeIndex) .add(constantsHolder.rewardPeriod()) .sub(constantsHolder.deltaPeriod()); } /** * @dev Performs emission of VerdictSent. * * Emits a {VerdictSent} event. */ function _emitVerdictsEvent( uint fromMonitorIndex, Verdict memory verdict, bool receiveVerdict ) private { uint previousBlockEvent = getLastReceivedVerdictBlock(verdict.toNodeIndex); lastVerdictBlocks[keccak256(abi.encodePacked(verdict.toNodeIndex))] = block.number; emit VerdictSent( fromMonitorIndex, verdict.toNodeIndex, verdict.downtime, verdict.latency, receiveVerdict, previousBlockEvent, block.timestamp, gasleft() ); } } contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No free Nodes available for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str()); string memory dkgRevert = "DKG process did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No free Nodes available for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); BountyV2(contractManager.getBounty()).handleNodeRemoving(nodes[nodeIndex].validatorId); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isAdmin(msg.sender) || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isAdmin(msg.sender) || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); _setNodeActive(nodeIndex); } function populateBountyV2(uint from, uint to) external onlyOwner { BountyV2 bounty = BountyV2(contractManager.getBounty()); uint nodeCreationWindow = bounty.nodeCreationWindowSeconds(); bounty.setNodeCreationWindowSeconds(uint(-1) / 2); for (uint nodeId = from; nodeId < _min(nodes.length, to); ++nodeId) { if (nodes[nodeId].status != NodeStatus.Left) { bounty.handleNodeCreation(nodes[nodeId].validatorId); } } bounty.setNodeCreationWindowSeconds(nodeCreationWindow); } /** * @dev Returns nodes with space availability. */ function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Returns IPs of active nodes. */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev Returns active nodes linked to the `msg.sender` (validator address). */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev Adds node to array. */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; BountyV2(contractManager.getBounty()).handleNodeCreation(validatorId); } /** * @dev Deletes node from array. */ function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } }
0x608060405234801561001057600080fd5b50600436106103785760003560e01c806391d14854116101d3578063c34da52411610104578063d12fa445116100a2578063d8f272e11161007c578063d8f272e114610797578063dcbaac60146107aa578063dcd3744d146107bd578063f5dc5442146107d257610378565b8063d12fa44514610769578063d45025f814610771578063d547741f1461078457610378565b8063c921ba68116100de578063c921ba681461071d578063c94f9c3d14610730578063c9e91c6614610743578063ca15c8731461075657610378565b8063c34da524146106e4578063c4d66de8146106f7578063c585d6041461070a57610378565b8063ab4df71e11610171578063b9f452471161014b578063b9f452471461068b578063bb4d53d61461069e578063be59bdc1146106b1578063c1ab2264146106d157610378565b8063ab4df71e14610668578063b39e12cf1461067b578063b81c806a1461068357610378565b8063a1a1ca5e116101ad578063a1a1ca5e14610625578063a217fddf14610645578063a4e692291461064d578063a910ede31461065557610378565b806391d14854146105ec57806396a0be4f146105ff5780639bcd95211461061257610378565b8063427cd6a6116102ad578063822a56281161024b5780638e001b7c116102255780638e001b7c146105935780639010d07c146105a657806390a98a89146105c657806390e848c0146105d957610378565b8063822a56281461056557806389f10228146105785780638d3a0f191461058057610378565b80636e23e8e5116102875780636e23e8e51461050b57806370d2fa181461051e57806379fe63081461053f578063819cdcd71461055257610378565b8063427cd6a6146104d25780635990e3cb146104e55780635b6b4185146104f857610378565b806322ef64fe1161031a57806336186464116102f4578063361864641461048657806336568abe14610499578063378bb226146104ac5780633d3be916146104bf57610378565b806322ef64fe1461044b578063248a9ca3146104605780632f2ff15d1461047357610378565b8063117066eb11610356578063117066eb146103ce578063125a0be2146103ee5780631c53c2801461040357806321c74e241461042b57610378565b806303dd6c271461037d57806308e85aab146103a65780630bdeab23146103bb575b600080fd5b61039061038b366004615206565b6107da565b60405161039d919061553f565b60405180910390f35b6103ae610855565b60405161039d919061551f565b6103ae6103c936600461512d565b61085b565b6103e16103dc366004615206565b610870565b60405161039d9190615514565b6104016103fc36600461512d565b6109e4565b005b610416610411366004615206565b610efc565b60405161039d9998979695949392919061557b565b61043e610439366004615206565b610ff0565b60405161039d9190615d00565b610453611049565b60405161039d91906154dc565b6103ae61046e366004615206565b6110d9565b61040161048136600461521e565b6110f1565b6103e161049436600461526e565b611139565b6104016104a736600461521e565b61114e565b6104536104ba366004615206565b611190565b6104016104cd36600461524d565b611310565b6103ae6104e036600461524d565b6115bb565b6103e16104f3366004615206565b6115e9565b6103e1610506366004615206565b611649565b610401610519366004615206565b611676565b61053161052c366004615206565b611822565b60405161039d929190615dc8565b6103e161054d366004615206565b611851565b6103e16105603660046152d0565b61187e565b6103ae610573366004615206565b611ac7565b6103ae611b14565b61040161058e366004615206565b611b1a565b6103ae6105a1366004615206565b611c3e565b6105b96105b436600461524d565b611d6c565b60405161039d9190615452565b6103ae6105d4366004615206565b611d93565b6104016105e736600461524d565b611da5565b6103e16105fa36600461521e565b612260565b6103e161060d366004615206565b61227e565b6103e1610620366004615206565b612293565b610638610633366004615206565b6122c0565b60405161039d9190615554565b6103ae612311565b6103ae612316565b6103e1610663366004615206565b612335565b61040161067636600461524d565b61259f565b6105b96126c4565b6103ae6126d3565b610401610699366004615206565b6126d9565b6104016106ac366004615165565b61287f565b6106c46106bf366004615206565b612cf5565b60405161039d9190615466565b6103ae6106df3660046152f4565b612d73565b6103e16106f23660046151bb565b612eb6565b61040161070536600461512d565b612f09565b6104536107183660046152f4565b612fa4565b6103ae61072b366004615206565b61317e565b61040161073e3660046152d0565b6131cb565b6103e161075136600461524d565b613306565b6103ae610764366004615206565b6137c6565b6104536137dd565b6103ae61077f366004615206565b61389e565b61040161079236600461521e565b6138eb565b6103ae6107a536600461532c565b613925565b6103e16107b8366004615206565b61393e565b6107c5613a64565b60405161039d919061548e565b6103ae613b28565b609854600090829081106108095760405162461bcd60e51b8152600401610800906159c4565b60405180910390fd5b609854831061082a5760405162461bcd60e51b8152600401610800906156df565b6098838154811061083757fe5b600091825260209091206009909102016001015460e01b9392505050565b60a15481565b609a6020526000908152604090206001015481565b609854600090829081106108965760405162461bcd60e51b8152600401610800906159c4565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b60208201526097549151633581777360e01b8152909133916001600160a01b03909116906335817773906108eb908590600401615568565b60206040518083038186803b15801561090357600080fd5b505afa158015610917573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061093b9190615149565b6001600160a01b031614806109535750610953613b2e565b61096f5760405162461bcd60e51b815260040161080090615c50565b61097884611851565b6109945760405162461bcd60e51b815260040161080090615b96565b61099d84613b3a565b7f8e9cdcada96a3b4c59c283849ac36354d89bc5c6ea79a1034f5272e677a5dc928442425a6040516109d29493929190615dad565b60405180910390a15060019392505050565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b60208201526097549151633581777360e01b8152909133916001600160a01b0390911690633581777390610a39908590600401615568565b60206040518083038186803b158015610a5157600080fd5b505afa158015610a65573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a899190615149565b6001600160a01b03161480610aa15750610aa1613b2e565b610abd5760405162461bcd60e51b815260040161080090615c50565b609754604051633581777360e01b81526000916001600160a01b031690633581777390610aec90600401615c87565b60206040518083038186803b158015610b0457600080fd5b505afa158015610b18573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3c9190615149565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610b7090600401615bfc565b60206040518083038186803b158015610b8857600080fd5b505afa158015610b9c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bc09190615149565b90506000826001600160a01b031663bad21775866040518263ffffffff1660e01b8152600401610bf09190615452565b60206040518083038186803b158015610c0857600080fd5b505afa158015610c1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c4091906152b8565b60405163f93c86f160e01b81529091506001600160a01b0384169063f93c86f190610c6f90849060040161551f565b60206040518083038186803b158015610c8757600080fd5b505afa158015610c9b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cbf91906151e6565b610cdb5760405162461bcd60e51b8152600401610800906158c7565b6000818152609f6020908152604091829020805483518184028101840190945280845260609392830182828015610d3157602002820191906000526020600020905b815481526020019060010190808311610d1d575b505050505090506000836001600160a01b0316631d703812846040518263ffffffff1660e01b8152600401610d66919061551f565b602060405180830381600087803b158015610d8057600080fd5b505af1158015610d94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db891906152b8565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610dec906004016157ce565b60206040518083038186803b158015610e0457600080fd5b505afa158015610e18573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e3c9190615149565b6001600160a01b031663ed089aa76040518163ffffffff1660e01b815260040160206040518083038186803b158015610e7457600080fd5b505afa158015610e88573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eac91906152b8565b905081610ed482610ec860018751613b8b90919063ffffffff16565b9063ffffffff613bb016565b1115610ef25760405162461bcd60e51b815260040161080090615874565b5050505050505050565b60988181548110610f0957fe5b60009182526020918290206009919091020180546040805160026001841615610100026000190190931692909204601f810185900485028301850190915280825291935091839190830182828015610fa25780601f10610f7757610100808354040283529160200191610fa2565b820191906000526020600020905b815481529060010190602001808311610f8557829003601f168201915b5050505060018301546004840154600585015460068601546007870154600890970154959660e085811b97640100000000870490911b9650600160401b90950461ffff169460ff9091169089565b609854600090829081106110165760405162461bcd60e51b8152600401610800906159c4565b6098838154811061102357fe5b6000918252602090912060099091020160010154600160401b900461ffff169392505050565b606060a05467ffffffffffffffff8111801561106457600080fd5b5060405190808252806020026020018201604052801561108e578160200160208202803683370190505b5090506000805b6098548110156110d4576110a881611851565b156110cc57808383815181106110ba57fe5b60209081029190910101526001909101905b600101611095565b505090565b6000818152606560205260409020600201545b919050565b60008281526065602052604090206002015461110f906105fa613bea565b61112b5760405162461bcd60e51b815260040161080090615690565b6111358282613bee565b5050565b609b6020526000908152604090205460ff1681565b611156613bea565b6001600160a01b0316816001600160a01b0316146111865760405162461bcd60e51b815260040161080090615cb1565b6111358282613c5d565b609754604051633581777360e01b81526060916000916001600160a01b03909116906335817773906111c490600401615c87565b60206040518083038186803b1580156111dc57600080fd5b505afa1580156111f0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112149190615149565b604051635be8c60f60e01b81529091506001600160a01b03821690635be8c60f9061124390869060040161551f565b60206040518083038186803b15801561125b57600080fd5b505afa15801561126f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061129391906151e6565b6112af5760405162461bcd60e51b815260040161080090615bc5565b6000838152609f60209081526040918290208054835181840281018401909452808452909183018282801561130357602002820191906000526020600020905b8154815260200190600101908083116112ef575b5050505050915050919050565b611318613b2e565b6113345760405162461bcd60e51b81526004016108009061570c565b6097546040805163f49bff7b60e01b815290516000926001600160a01b03169163f49bff7b916004808301926020929190829003018186803b15801561137957600080fd5b505afa15801561138d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113b19190615149565b90506000816001600160a01b0316632e2337886040518163ffffffff1660e01b815260040160206040518083038186803b1580156113ee57600080fd5b505afa158015611402573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061142691906152b8565b60405163022d262360e01b81529091506001600160a01b0383169063022d26239061145c906001600160ff1b039060040161551f565b600060405180830381600087803b15801561147657600080fd5b505af115801561148a573d6000803e3d6000fd5b5086925050505b60985461149e9085613ccc565b811015611560576002609882815481106114b457fe5b600091825260209091206007600990920201015460ff1660038111156114d657fe5b1461155857826001600160a01b031663c664ccf5609883815481106114f757fe5b9060005260206000209060090201600801546040518263ffffffff1660e01b8152600401611525919061551f565b600060405180830381600087803b15801561153f57600080fd5b505af1158015611553573d6000803e3d6000fd5b505050505b600101611491565b5060405163022d262360e01b81526001600160a01b0383169063022d26239061158d90849060040161551f565b600060405180830381600087803b1580156115a757600080fd5b505af1158015610ef2573d6000803e3d6000fd5b609f60205281600052604060002081815481106115d457fe5b90600052602060002001600091509150505481565b6098546000908290811061160f5760405162461bcd60e51b8152600401610800906159c4565b60035b6098848154811061161f57fe5b600091825260209091206007600990920201015460ff16600381111561164157fe5b149392505050565b6098546000908290811061166f5760405162461bcd60e51b8152600401610800906159c4565b6001611612565b60006098828154811061168557fe5b600091825260209091206007600990920201015460ff1660038111156116a757fe5b146116c45760405162461bcd60e51b815260040161080090615622565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906116f390600401615c87565b60206040518083038186803b15801561170b57600080fd5b505afa15801561171f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117439190615149565b9050600061175083611ac7565b9050600061175d33613ce4565b8061176d575061176d3385612eb6565b9050806117f657604051630ba7341960e11b815282906001600160a01b0385169063174e6832906117a2903390600401615452565b60206040518083038186803b1580156117ba57600080fd5b505afa1580156117ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117f291906152b8565b1490505b806118135760405162461bcd60e51b81526004016108009061594a565b61181c84613e5f565b50505050565b6099818154811061182f57fe5b60009182526020909120600290910201805460019091015460ff909116915082565b609854600090829081106118775760405162461bcd60e51b8152600401610800906159c4565b6000611612565b609854600090839081106118a45760405162461bcd60e51b8152600401610800906159c4565b604080518082018252600c81526b2737b232a937ba30ba34b7b760a11b60208083019190915282518084018452600f81526e14d8da185a5b9cd25b9d195c9b985b608a1b918101919091526097549251633581777360e01b81529192909133916001600160a01b031690633581777390611922908690600401615568565b60206040518083038186803b15801561193a57600080fd5b505afa15801561194e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119729190615149565b6001600160a01b03161480611a0d5750609754604051633581777360e01b815233916001600160a01b0316906335817773906119b2908590600401615568565b60206040518083038186803b1580156119ca57600080fd5b505afa1580156119de573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a029190615149565b6001600160a01b0316145b80611a1b5750611a1b613b2e565b611a375760405162461bcd60e51b815260040161080090615c50565b8460ff1660998781548110611a4857fe5b600091825260209091206002909102015460ff161015611a6b5760009350611abe565b60ff851615611ab957611ab986611ab4611aaf8860ff1660998b81548110611a8f57fe5b600091825260209091206002909102015460ff169063ffffffff613eb416565b613ef6565b613f1d565b600193505b50505092915050565b60985460009082908110611aed5760405162461bcd60e51b8152600401610800906159c4565b60988381548110611afa57fe5b906000526020600020906009020160080154915050919050565b60a25481565b60985481908110611b3d5760405162461bcd60e51b8152600401610800906159c4565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b60208201526097549151633581777360e01b8152909133916001600160a01b0390911690633581777390611b92908590600401615568565b60206040518083038186803b158015611baa57600080fd5b505afa158015611bbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611be29190615149565b6001600160a01b03161480611bfa5750611bfa613b2e565b611c165760405162461bcd60e51b815260040161080090615c50565b4260988481548110611c2457fe5b906000526020600020906009020160050181905550505050565b60985460009082908110611c645760405162461bcd60e51b8152600401610800906159c4565b609760009054906101000a90046001600160a01b03166001600160a01b031663f49bff7b6040518163ffffffff1660e01b815260040160206040518083038186803b158015611cb257600080fd5b505afa158015611cc6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cea9190615149565b6001600160a01b031663a43d8437846040518263ffffffff1660e01b8152600401611d15919061551f565b60206040518083038186803b158015611d2d57600080fd5b505afa158015611d41573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d6591906152b8565b9392505050565b6000828152606560205260408120611d8a908363ffffffff61412d16565b90505b92915050565b609d6020526000908152604090205481565b60985481908110611dc85760405162461bcd60e51b8152600401610800906159c4565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b60208201526097549151633581777360e01b8152909133916001600160a01b0390911690633581777390611e1d908590600401615568565b60206040518083038186803b158015611e3557600080fd5b505afa158015611e49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e6d9190615149565b6001600160a01b03161480611e855750611e85613b2e565b611ea15760405162461bcd60e51b815260040161080090615c50565b609754604051633581777360e01b81526000916001600160a01b031690633581777390611ed090600401615c87565b60206040518083038186803b158015611ee857600080fd5b505afa158015611efc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f209190615149565b604051635be8c60f60e01b81529091506001600160a01b03821690635be8c60f90611f4f90889060040161551f565b60206040518083038186803b158015611f6757600080fd5b505afa158015611f7b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f9f91906151e6565b611fbb5760405162461bcd60e51b815260040161080090615bc5565b6000858152609f602090815260409182902080548351818402810184019094528084526060939283018282801561201157602002820191906000526020600020905b815481526020019060010190808311611ffd575b5050505050905060006120248287614139565b90508151811015612090576000878152609f60205260409020825161205090600163ffffffff613eb416565b8154811061205a57fe5b9060005260206000200154609f6000898152602001908152602001600020828154811061208357fe5b6000918252602090912001555b6000878152609f602052604090208054806120a757fe5b600190038181906000526020600020016000905590556000612111609888815481106120cf57fe5b6000918252602090912060408051808201918290529260090290910160029081019182845b8154815260200190600101908083116120f4575050505050614179565b905087846001600160a01b031663bad21775836040518263ffffffff1660e01b81526004016121409190615452565b60206040518083038186803b15801561215857600080fd5b505afa15801561216c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061219091906152b8565b1415610ef2576001600160a01b0381166000908152609a60205260409020600190810154141561221b57604051630601a91b60e21b81526001600160a01b03851690631806a46c906121e8908b908590600401615528565b600060405180830381600087803b15801561220257600080fd5b505af1158015612216573d6000803e3d6000fd5b505050505b6001600160a01b03166000818152609a602081815260408084209a84528a82528320805460ff1916905592909152905250505060019092018054600019019055505050565b6000828152606560205260408120611d8a908363ffffffff61420116565b609c6020526000908152604090205460ff1681565b609854600090829081106122b95760405162461bcd60e51b8152600401610800906159c4565b6002611612565b609854600090829081106122e65760405162461bcd60e51b8152600401610800906159c4565b609883815481106122f357fe5b600091825260209091206009909102016007015460ff169392505050565b600081565b600061232f60a15460a054613b8b90919063ffffffff16565b90505b90565b6098546000908290811061235b5760405162461bcd60e51b8152600401610800906159c4565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b60208201526097549151633581777360e01b8152909133916001600160a01b03909116906335817773906123b0908590600401615568565b60206040518083038186803b1580156123c857600080fd5b505afa1580156123dc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124009190615149565b6001600160a01b031614806124185750612418613b2e565b6124345760405162461bcd60e51b815260040161080090615c50565b61243d84611649565b6124595760405162461bcd60e51b815260040161080090615997565b61246284614216565b61246b846143d6565b609760009054906101000a90046001600160a01b03166001600160a01b031663f49bff7b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156124b957600080fd5b505afa1580156124cd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124f19190615149565b6001600160a01b031663dcd7e9ca6098868154811061250c57fe5b9060005260206000209060090201600801546040518263ffffffff1660e01b815260040161253a919061551f565b600060405180830381600087803b15801561255457600080fd5b505af1158015612568573d6000803e3d6000fd5b505050507f07903541c5c6f3b94d75bbe8eba01679f00857bb87e7d2c2b5eb36fcab0e20a684425a6040516109d293929190615d97565b609854829081106125c25760405162461bcd60e51b8152600401610800906159c4565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b60208201526097549151633581777360e01b8152909133916001600160a01b0390911690633581777390612617908590600401615568565b60206040518083038186803b15801561262f57600080fd5b505afa158015612643573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126679190615149565b6001600160a01b0316148061267f575061267f613b2e565b61269b5760405162461bcd60e51b815260040161080090615c50565b82609885815481106126a957fe5b90600052602060002090600902016006018190555050505050565b6097546001600160a01b031681565b60985490565b6003609882815481106126e857fe5b600091825260209091206007600990920201015460ff16600381111561270a57fe5b146127275760405162461bcd60e51b8152600401610800906155eb565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061275690600401615c87565b60206040518083038186803b15801561276e57600080fd5b505afa158015612782573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127a69190615149565b905060006127b383611ac7565b905060006127c033613ce4565b806127d057506127d03385612eb6565b90508061285957604051630ba7341960e11b815282906001600160a01b0385169063174e683290612805903390600401615452565b60206040518083038186803b15801561281d57600080fd5b505afa158015612831573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061285591906152b8565b1490505b806128765760405162461bcd60e51b81526004016108009061594a565b61181c8461459a565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b60208201526097549151633581777360e01b8152909133916001600160a01b03909116906335817773906128d4908590600401615568565b60206040518083038186803b1580156128ec57600080fd5b505afa158015612900573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129249190615149565b6001600160a01b0316148061293c575061293c613b2e565b6129585760405162461bcd60e51b815260040161080090615c50565b612968604083016020840161526e565b6001600160e01b031916158015906129af5750609b600061298f604085016020860161526e565b6001600160e01b031916815260208101919091526040016000205460ff16155b6129cb5760405162461bcd60e51b815260040161080090615788565b609c60006129d98480615ddb565b6040516020016129ea92919061538b565b60408051601f198184030181529181528151602092830120835290820192909252016000205460ff1615612a305760405162461bcd60e51b815260040161080090615913565b6000612a426080840160608501615296565b61ffff1611612a635760405162461bcd60e51b815260040161080090615c2a565b604080518082018252612a919160808501906002908390839080828437600092019190915250614179915050565b6001600160a01b0316836001600160a01b031614612ac15760405162461bcd60e51b815260040161080090615a57565b609754604051633581777360e01b81526000916001600160a01b031690633581777390612af090600401615c87565b60206040518083038186803b158015612b0857600080fd5b505afa158015612b1c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b409190615149565b6001600160a01b031663bad21775856040518263ffffffff1660e01b8152600401612b6b9190615452565b60206040518083038186803b158015612b8357600080fd5b505afa158015612b97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bbb91906152b8565b90506000612c5f85612bcd8680615ddb565b8080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250612c1292505050604088016020890161526e565b612c226060890160408a0161526e565b612c3260808a0160608b01615296565b6040805180820182529060808c019060029083908390808284376000920191909152508a91506145e99050565b90507f1af6b8442f2c99735a0286ab2f8e6ac963401b07d10ebc79cd9805fdd37986cc8186612c8e8780615ddb565b612c9e60408a0160208b0161526e565b612cae60608b0160408c0161526e565b612cbe60808c0160608d01615296565b612cce60e08d0160c08e01615296565b425a604051612ce69a99989796959493929190615d0f565b60405180910390a15050505050565b612cfd61504e565b60985482908110612d205760405162461bcd60e51b8152600401610800906159c4565b60988381548110612d2d57fe5b60009182526020918290206040805180820191829052600990930290910160028181018054855293949092916003019085018083116112ef575050505050915050919050565b609754604051633581777360e01b815260009182916001600160a01b0390911690633581777390612da6906004016157ce565b60206040518083038186803b158015612dbe57600080fd5b505afa158015612dd2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612df69190615149565b9050600091506000816001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b158015612e3757600080fd5b505afa158015612e4b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e6f9190615310565b60ff169050835b818160ff1611612eae5760ff81166000908152609e6020526040902054612ea490859063ffffffff613b8b16565b9350600101612e76565b505050919050565b60985460009082908110612edc5760405162461bcd60e51b8152600401610800906159c4565b50506001600160a01b03919091166000908152609a60209081526040808320938352929052205460ff1690565b600054610100900460ff1680612f225750612f22614c11565b80612f30575060005460ff16155b612f4c5760405162461bcd60e51b815260040161080090615b06565b600054610100900460ff16158015612f77576000805460ff1961ff0019909116610100171660011790555b612f8082614c17565b600060a081905560a181905560a2558015611135576000805461ff00191690555050565b609754604051633581777360e01b81526060916000916001600160a01b0390911690633581777390612fd8906004016157ce565b60206040518083038186803b158015612ff057600080fd5b505afa158015613004573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130289190615149565b9050606061303584612d73565b67ffffffffffffffff8111801561304b57600080fd5b50604051908082528060200260200182016040528015613075578160200160208202803683370190505b50905060008090506000836001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b1580156130b857600080fd5b505afa1580156130cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130f09190615310565b60ff169050855b818160ff16116131735760005b60ff82166000908152609e602052604090205481101561316a5760ff82166000908152609e6020526040902080548290811061313c57fe5b906000526020600020015485858151811061315357fe5b602090810291909101015260019384019301613104565b506001016130f7565b509195945050505050565b609854600090829081106131a45760405162461bcd60e51b8152600401610800906159c4565b609883815481106131b157fe5b906000526020600020906009020160050154915050919050565b609854829081106131ee5760405162461bcd60e51b8152600401610800906159c4565b604080518082018252600781526653636861696e7360c81b60208201526097549151633581777360e01b8152909133916001600160a01b039091169063358177739061323e908590600401615568565b60206040518083038186803b15801561325657600080fd5b505afa15801561326a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061328e9190615149565b6001600160a01b031614806132a657506132a6613b2e565b6132c25760405162461bcd60e51b815260040161080090615c50565b60ff83161561181c5761181c84611ab4611aaf8660ff16609989815481106132e657fe5b600091825260209091206002909102015460ff169063ffffffff613b8b16565b6098546000908290811061332c5760405162461bcd60e51b8152600401610800906159c4565b6040805180820182526006815265426f756e747960d01b60208201526097549151633581777360e01b8152909133916001600160a01b039091169063358177739061337b908590600401615568565b60206040518083038186803b15801561339357600080fd5b505afa1580156133a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133cb9190615149565b6001600160a01b031614806133e357506133e3613b2e565b6133ff5760405162461bcd60e51b815260040161080090615c50565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061342e90600401615bfc565b60206040518083038186803b15801561344657600080fd5b505afa15801561345a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061347e9190615149565b609754604051633581777360e01b81529192506000916001600160a01b03909116906335817773906134b290600401615c87565b60206040518083038186803b1580156134ca57600080fd5b505afa1580156134de573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906135029190615149565b604051635be8c60f60e01b81529091506001600160a01b03821690635be8c60f90613531908a9060040161551f565b60206040518083038186803b15801561354957600080fd5b505afa15801561355d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061358191906151e6565b61359d5760405162461bcd60e51b815260040161080090615bc5565b6000878152609f60209081526040918290208054835181840281018401909452808452606093928301828280156135f357602002820191906000526020600020905b8154815260200190600101908083116135df575b5050505050905060006136068289614139565b9050815181106136285760405162461bcd60e51b81526004016108009061582e565b604051630eb81c0960e11b81526000906001600160a01b03861690631d70381290613657908d9060040161551f565b602060405180830381600087803b15801561367157600080fd5b505af1158015613685573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136a991906152b8565b609754604051633581777360e01b81529192506000916001600160a01b03909116906335817773906136dd906004016157ce565b60206040518083038186803b1580156136f557600080fd5b505afa158015613709573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061372d9190615149565b6001600160a01b031663ed089aa76040518163ffffffff1660e01b815260040160206040518083038186803b15801561376557600080fd5b505afa158015613779573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061379d91906152b8565b9050816137b582610ec886600163ffffffff613b8b16565b11159b9a5050505050505050505050565b6000818152606560205260408120611d8d90614cb6565b336000908152609a602052604090206001015460609067ffffffffffffffff8111801561380957600080fd5b50604051908082528060200260200182016040528015613833578160200160208202803683370190505b5090506000805b6098548110156110d457336000908152609a6020908152604080832084845290915290205460ff168015613872575061387281611851565b15613896578083838151811061388457fe5b60209081029190910101526001909101905b60010161383a565b609854600090829081106138c45760405162461bcd60e51b8152600401610800906159c4565b609883815481106138d157fe5b906000526020600020906009020160060154915050919050565b600082815260656020526040902060020154613909906105fa613bea565b6111865760405162461bcd60e51b815260040161080090615a07565b609e60205281600052604060002081815481106115d457fe5b609854600090829081106139645760405162461bcd60e51b8152600401610800906159c4565b6097546040805163f49bff7b60e01b8152905142926001600160a01b03169163f49bff7b916004808301926020929190829003018186803b1580156139a857600080fd5b505afa1580156139bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139e09190615149565b6001600160a01b031663a43d8437856040518263ffffffff1660e01b8152600401613a0b919061551f565b60206040518083038186803b158015613a2357600080fd5b505afa158015613a37573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a5b91906152b8565b11159392505050565b606060a05467ffffffffffffffff81118015613a7f57600080fd5b50604051908082528060200260200182016040528015613aa9578160200160208202803683370190505b5090506000805b6098548110156110d457613ac381611851565b15613b205760988181548110613ad557fe5b906000526020600020906009020160010160009054906101000a900460e01b838381518110613b0057fe5b6001600160e01b0319909216602092830291909101909101526001909101905b600101613ab0565b60a05481565b600061232f8133612260565b600160988281548110613b4957fe5b60009182526020909120600760099092020101805460ff19166001836003811115613b7057fe5b02179055505060a0805460001901905560a180546001019055565b600082820183811015611d8a5760405162461bcd60e51b8152600401610800906157f7565b600082613bbf57506000611d8d565b82820282848281613bcc57fe5b0414611d8a5760405162461bcd60e51b815260040161080090615a8e565b3390565b6000828152606560205260409020613c0c908263ffffffff614cc116565b1561113557613c19613bea565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000828152606560205260409020613c7b908263ffffffff614cd616565b1561113557613c88613bea565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b600081831015613cdd575081611d8d565b5080611d8d565b60975460405160009182916001600160a01b039091169063ec56a37390613d0d9060200161543a565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401613d3f919061551f565b60206040518083038186803b158015613d5757600080fd5b505afa158015613d6b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d8f9190615149565b90506001600160a01b03811615613e4f576000819050806001600160a01b03166391d14854604051613dc090615424565b6040519081900381206001600160e01b031960e084901b168252613de8918890600401615528565b60206040518083038186803b158015613e0057600080fd5b505afa158015613e14573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e3891906151e6565b80613e465750613e46613b2e565b925050506110ec565b613e57613b2e565b9150506110ec565b600360988281548110613e6e57fe5b60009182526020909120600760099092020101805460ff19166001836003811115613e9557fe5b021790555060a054613eae90600163ffffffff613eb416565b60a05550565b6000611d8a83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250614ceb565b60006101008210613f195760405162461bcd60e51b815260040161080090615743565b5090565b600060998381548110613f2c57fe5b600091825260208220600290910201546099805460ff90921693509085908110613f5257fe5b60009182526020808320600160029093020182015460ff86168452609e909152604090922054919250613f8b919063ffffffff613eb416565b8110156140625760ff82166000908152609e602052604081208054613fb790600163ffffffff613eb416565b81548110613fc157fe5b9060005260206000200154905080609e60008560ff1660ff1681526020019081526020016000208381548110613ff357fe5b9060005260206000200181905550816099828154811061400f57fe5b906000526020600020906002020160010181905550609e60008460ff1660ff16815260200190815260200160002080548061404657fe5b6001900381819060005260206000200160009055905550614094565b60ff82166000908152609e6020526040902080548061407d57fe5b600190038181906000526020600020016000905590555b60ff83166000908152609e602090815260408220805460018101825590835291200184905560998054849190869081106140ca57fe5b60009182526020808320600292909202909101805460ff191660ff9485161790559185168152609e9091526040902054614105906001613eb4565b6099858154811061411257fe5b90600052602060002090600202016001018190555050505050565b6000611d8a8383614d17565b6000805b8351811015614170578284828151811061415357fe5b60200260200101511415614168579050611d8d565b60010161413d565b50509051919050565b805160208083015160405160009384936141959391920161537d565b60408051601f19818403018152919052805160209091012090506000600c5b60208160ff1610156141f657600c810360080260ff16838260ff16602081106141d957fe5b1a60f81b6001600160f81b031916901c91909117906001016141b4565b5060601c9392505050565b6000611d8a836001600160a01b038416614d5c565b6000609b60006098848154811061422957fe5b600091825260208083206009929092029091016001015460e01b6001600160e01b03191683528201929092526040018120805460ff19169215159290921790915560988054609c9183918590811061427d57fe5b906000526020600020906009020160000160405160200161429e91906153b7565b60405160208183030381529060405280519060200120815260200190815260200160002060006101000a81548160ff021916908315150217905550609d6000609883815481106142ea57fe5b906000526020600020906009020160000160405160200161430b91906153b7565b604051602081830303815290604052805190602001208152602001908152602001600020600090556000600381111561434057fe5b6098828154811061434d57fe5b600091825260209091206007600990920201015460ff16600381111561436f57fe5b14156143845760a0805460001901905561438f565b60a180546000190190555b60026098828154811061439e57fe5b60009182526020909120600760099092020101805460ff191660018360038111156143c557fe5b02179055505060a280546001019055565b6000609982815481106143e557fe5b600091825260208220600290910201546099805460ff9092169350908490811061440b57fe5b60009182526020808320600160029093020182015460ff86168452609e909152604090922054919250614444919063ffffffff613eb416565b81101561451b5760ff82166000908152609e60205260408120805461447090600163ffffffff613eb416565b8154811061447a57fe5b9060005260206000200154905080609e60008560ff1660ff16815260200190815260200160002083815481106144ac57fe5b906000526020600020018190555081609982815481106144c857fe5b906000526020600020906002020160010181905550609e60008460ff1660ff1681526020019081526020016000208054806144ff57fe5b600190038181906000526020600020016000905590555061454d565b60ff82166000908152609e6020526040902080548061453657fe5b600190038181906000526020600020016000905590555b6099838154811061455a57fe5b60009182526020909120600290910201805460ff19169055609980548490811061458057fe5b906000526020600020906002020160010160009055505050565b6000609882815481106145a957fe5b60009182526020909120600760099092020101805460ff191660018360038111156145d057fe5b021790555060a054613eae90600163ffffffff613b8b16565b609754604051633581777360e01b815260009182916001600160a01b039091169063358177739061461c906004016157ce565b60206040518083038186803b15801561463457600080fd5b505afa158015614648573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061466c9190615149565b905060986040518061014001604052808a8152602001896001600160e01b0319168152602001886001600160e01b03191681526020018761ffff16815260200186815260200143815260200142815260200160008152602001600060038111156146d257fe5b81526020908101869052825460018101845560009384529281902082518051939460090290910192614707928492019061506c565b5060208201516001820180546040850151606086015161ffff16600160401b0269ffff00000000000000001960e092831c6401000000000267ffffffff00000000199690931c63ffffffff1990941693909317949094161716919091179055608082015161477b90600280840191906150e6565b5060a0820151600482015560c0820151600582015560e0820151600682015561010082015160078201805460ff191660018360038111156147b857fe5b021790555061012091909101516008909101556098546147df90600163ffffffff613eb416565b6000848152609f60209081526040808320805460018101825590845282842001849055519294509091614814918b910161539b565b6040516020818303038152906040528051906020012090506001609b60008a6001600160e01b0319166001600160e01b031916815260200190815260200160002060006101000a81548160ff0219169083151502179055506001609c600083815260200190815260200160002060006101000a81548160ff02191690831515021790555082609d6000838152602001908152602001600020819055506001609a60008c6001600160a01b03166001600160a01b03168152602001908152602001600020600001600085815260200190815260200160002060006101000a81548160ff021916908315150217905550609a60008b6001600160a01b03166001600160a01b031681526020019081526020016000206001016000815480929190600101919050555060996040518060400160405280846001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b15801561498057600080fd5b505afa158015614994573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906149b89190615310565b60ff168152602001609e6000866001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b1580156149fd57600080fd5b505afa158015614a11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614a359190615310565b60ff908116825260208083019390935260409182016000908120549094528554600180820188559685528385208651600290920201805460ff191691909216178155938201519390940192909255825163c83ee0b360e01b81529251609e9391926001600160a01b0387169263c83ee0b39260048083019392829003018186803b158015614ac257600080fd5b505afa158015614ad6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614afa9190615310565b60ff168152602080820192909252604090810160009081208054600181810183559183529184902090910186905560a080549091019055609754815163f49bff7b60e01b815291516001600160a01b039091169263f49bff7b9260048082019391829003018186803b158015614b6f57600080fd5b505afa158015614b83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614ba79190615149565b6001600160a01b031663c664ccf5856040518263ffffffff1660e01b8152600401614bd2919061551f565b600060405180830381600087803b158015614bec57600080fd5b505af1158015614c00573d6000803e3d6000fd5b505050505050979650505050505050565b303b1590565b600054610100900460ff1680614c305750614c30614c11565b80614c3e575060005460ff16155b614c5a5760405162461bcd60e51b815260040161080090615b06565b600054610100900460ff16158015614c85576000805460ff1961ff0019909116610100171660011790555b614c8d614d74565b614c9860003361112b565b614ca182614e07565b8015611135576000805461ff00191690555050565b6000611d8d82614e7d565b6000611d8a836001600160a01b038416614e81565b6000611d8a836001600160a01b038416614ecb565b60008184841115614d0f5760405162461bcd60e51b81526004016108009190615568565b505050900390565b81546000908210614d3a5760405162461bcd60e51b81526004016108009061564e565b826000018281548110614d4957fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600054610100900460ff1680614d8d5750614d8d614c11565b80614d9b575060005460ff16155b614db75760405162461bcd60e51b815260040161080090615b06565b600054610100900460ff16158015614de2576000805460ff1961ff0019909116610100171660011790555b614dea614f91565b614df2614f91565b8015614e04576000805461ff00191690555b50565b6001600160a01b038116614e2d5760405162461bcd60e51b815260040161080090615b54565b614e3f816001600160a01b0316615012565b614e5b5760405162461bcd60e51b815260040161080090615acf565b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b6000614e8d8383614d5c565b614ec357508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155611d8d565b506000611d8d565b60008181526001830160205260408120548015614f875783546000198083019190810190600090879083908110614efe57fe5b9060005260206000200154905080876000018481548110614f1b57fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080614f4b57fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050611d8d565b6000915050611d8d565b600054610100900460ff1680614faa5750614faa614c11565b80614fb8575060005460ff16155b614fd45760405162461bcd60e51b815260040161080090615b06565b600054610100900460ff16158015614df2576000805460ff1961ff0019909116610100171660011790558015614e04576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061504657508115155b949350505050565b60405180604001604052806002906020820280368337509192915050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106150ad57805160ff19168380011785556150da565b828001600101855582156150da579182015b828111156150da5782518255916020019190600101906150bf565b50613f19929150615113565b82600281019282156150da57916020028201828111156150da5782518255916020019190600101906150bf565b61233291905b80821115613f195760008155600101615119565b60006020828403121561513e578081fd5b8135611d8a81615e55565b60006020828403121561515a578081fd5b8151611d8a81615e55565b60008060408385031215615177578081fd5b823561518281615e55565b9150602083013567ffffffffffffffff81111561519d578182fd5b80840160e081870312156151af578283fd5b80925050509250929050565b600080604083850312156151cd578182fd5b82356151d881615e55565b946020939093013593505050565b6000602082840312156151f7578081fd5b81518015158114611d8a578182fd5b600060208284031215615217578081fd5b5035919050565b60008060408385031215615230578182fd5b82359150602083013561524281615e55565b809150509250929050565b6000806040838503121561525f578182fd5b50508035926020909101359150565b60006020828403121561527f578081fd5b81356001600160e01b031981168114611d8a578182fd5b6000602082840312156152a7578081fd5b813561ffff81168114611d8a578182fd5b6000602082840312156152c9578081fd5b5051919050565b600080604083850312156152e2578182fd5b82359150602083013561524281615e6a565b600060208284031215615305578081fd5b8135611d8a81615e6a565b600060208284031215615321578081fd5b8151611d8a81615e6a565b6000806040838503121561533e578182fd5b82356151d881615e6a565b60008151808452615361816020860160208601615e29565b601f01601f19169290920160200192915050565b61ffff169052565b918252602082015260400190565b6000828483379101908152919050565b600082516153ad818460208701615e29565b9190910192915050565b60008083546001808216600081146153d657600181146153ed57613173565b60ff198316865260028304607f1686019350613173565b600283048786526020808720875b838110156154145781548a8201529085019082016153fb565b5050509095019695505050505050565b6941444d494e5f524f4c4560b01b8152600a0190565b6b29b5b0b632a6b0b730b3b2b960a11b8152600c0190565b6001600160a01b0391909116815260200190565b60408101818360005b6002811015611abe57815183526020928301929091019060010161546f565b6020808252825182820181905260009190848201906040850190845b818110156154d05783516001600160e01b031916835292840192918401916001016154aa565b50909695505050505050565b6020808252825182820181905260009190848201906040850190845b818110156154d0578351835292840192918401916001016154f8565b901515815260200190565b90815260200190565b9182526001600160a01b0316602082015260400190565b6001600160e01b031991909116815260200190565b602081016004831061556257fe5b91905290565b600060208252611d8a6020830184615349565b600061012080835261558f8184018d615349565b6001600160e01b03198c811660208601528b16604085015261ffff8a1660608501526080840189905260a0840188905260c08401879052915050600484106155d357fe5b60e08201939093526101000152979650505050505050565b6020808252601a908201527f4e6f6465206973206e6f7420496e204d61696e74656e616e6365000000000000604082015260600190565b6020808252601290820152714e6f6465206973206e6f742041637469766560701b604082015260600190565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b602080825260139082015272139bd91948191bd95cc81b9bdd08195e1a5cdd606a1b604082015260600190565b60208082526017908201527f43616c6c6572206973206e6f7420746865206f776e6572000000000000000000604082015260600190565b60208082526025908201527f53616665436173743a2076616c756520646f65736e27742066697420696e2038604082015264206269747360d81b606082015260800190565b60208082526026908201527f49502061646472657373206973207a65726f206f72206973206e6f7420617661604082015265696c61626c6560d01b606082015260800190565b6020808252600f908201526e21b7b739ba30b73a39a437b63232b960891b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526026908201527f4e6f646520646f6573206e6f7420657869737420666f7220746869732056616c60408201526534b230ba37b960d11b606082015260800190565b60208082526033908201527f56616c696461746f72206d757374206d65657420746865204d696e696d756d2060408201527214dd185ada5b99c814995c5d5a5c995b595b9d606a1b606082015260800190565b6020808252602c908201527f56616c696461746f72206973206e6f7420617574686f72697a656420746f206360408201526b72656174652061206e6f646560a01b606082015260800190565b6020808252601a908201527f4e616d6520697320616c72656164792072656769737465726564000000000000604082015260600190565b6020808252602d908201527f53656e646572206973206e6f74207065726d697474656420746f2063616c6c2060408201526c3a3434b990333ab731ba34b7b760991b606082015260800190565b6020808252601390820152724e6f6465206973206e6f74204c656176696e6760681b604082015260600190565b60208082526023908201527f4e6f64652077697468207375636820696e64657820646f6573206e6f742065786040820152621a5cdd60ea1b606082015260800190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526017908201527f5075626c6963204b657920697320696e636f7272656374000000000000000000604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526017908201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b60208082526022908201527f436f6e74726163744d616e616765722061646472657373206973206e6f742073604082015261195d60f21b606082015260800190565b6020808252601590820152744e6f64652073686f756c642062652041637469766560581b604082015260600190565b6020808252601b908201527f56616c696461746f7220494420646f6573206e6f742065786973740000000000604082015260600190565b6020808252601490820152732232b632b3b0ba34b7b721b7b73a3937b63632b960611b604082015260600190565b6020808252600c908201526b506f7274206973207a65726f60a01b604082015260600190565b60208082526019908201527f4d6573736167652073656e64657220697320696e76616c696400000000000000604082015260600190565b60208082526010908201526f56616c696461746f725365727669636560801b604082015260600190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b61ffff91909116815260200190565b8a81526001600160a01b038a1660208201526101206040820181905281018890526000610140898b82850137828a018101919091526001600160e01b031988811660608401528716608083015261ffff861660a0830152601f8901601f1916820101615d7e60c0830186615375565b60e0820193909352610100015298975050505050505050565b9283526020830191909152604082015260600190565b93845260208401929092526040830152606082015260800190565b60ff929092168252602082015260400190565b6000808335601e19843603018112615df1578283fd5b8084018035925067ffffffffffffffff831115615e0c578384fd5b60200192505036819003821315615e2257600080fd5b9250929050565b60005b83811015615e44578181015183820152602001615e2c565b8381111561181c5750506000910152565b6001600160a01b0381168114614e0457600080fd5b60ff81168114614e0457600080fdfea26469706673582212200588a31495adba19b3b203ea6f32092d4a8b0478c0b5b3da90c1cbc2b3a5255364736f6c634300060a0033
[ 0, 4, 7, 9, 6, 10 ]
0x4533e685fe1441b09ff7d45397f8d777cef61561
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; 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); } } } } 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 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"); } } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface TreasuryPool { function updateNextRewards(uint256 amount) external; } contract GAMERReserves { // Token that serves as a reserve for GAMER address public reserveToken; address public gov; address public pendingGov; address public rebaser; address public gamerAddress; address public treasuryPool; /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Event emitted when TreasuryPool is changed */ event NewTreasuryPool(address oldTreasuryPool, address newTreasuryPool); /** * @notice Event emitted when rebaser is changed */ event NewRebaser(address oldRebaser, address newRebaser); modifier onlyGov() { require(msg.sender == gov); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } constructor( address reserveToken_, address gamerAddress_ ) public { reserveToken = reserveToken_; gamerAddress = gamerAddress_; gov = msg.sender; } function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; GAMERTokenInterface(gamerAddress).decreaseAllowance(oldRebaser, uint256(-1)); rebaser = rebaser_; GAMERTokenInterface(gamerAddress).approve(rebaser_, uint256(-1)); emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** * @notice lets msg.sender accept governance */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice sets the treasuryPool * @param treasuryPool_ The address of the treasury pool contract. */ function _setTreasuryPool(address treasuryPool_) external onlyGov { address oldTreasuryPool = treasuryPool; treasuryPool = treasuryPool_; emit NewTreasuryPool(oldTreasuryPool, treasuryPool_); } /// @notice Moves all tokens to a new reserve contract function migrateReserves( address newReserve, address[] memory tokens ) public onlyGov { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); uint256 bal = token.balanceOf(address(this)); SafeERC20.safeTransfer(token, newReserve, bal); } } /// @notice Gets the current amount of reserves token held by this contract function reserves() public view returns (uint256) { return IERC20(reserveToken).balanceOf(address(this)); } /// @notice Gets the current amount of reserves token held by this contract function distributeTreasuryReward(uint256 amount) public onlyRebaser { IERC20(reserveToken).transfer(treasuryPool, amount); TreasuryPool(treasuryPool).updateNextRewards(amount); } } contract GAMERGovernanceStorage { /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } contract GAMERTokenStorage { using SafeMath for uint256; /** * @dev Guard variable for re-entrancy checks. Not currently used */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved rebaser for this contract */ address public rebaser; /** * @notice Reserve address of GAMER protocol */ address public incentivizer; /** * @notice stakingPool address of GAMER protocol */ address public stakingPool; /** * @notice teamPool address of GAMER protocol */ address public teamPool; /** * @notice dev address of GAMER protocol */ address public dev; /** * @notice Total supply of GAMERs */ uint256 internal _totalSupply; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**24; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**18; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public gamersScalingFactor; mapping (address => uint256) internal _gamerBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; uint256 public initSupply; } contract GAMERTokenInterface is GAMERTokenStorage, GAMERGovernanceStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Event emitted when tokens are rebased */ event Rebase(uint256 epoch, uint256 prevGrapsScalingFactor, uint256 newGrapsScalingFactor); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Sets the rebaser contract */ event NewRebaser(address oldRebaser, address newRebaser); /** * @notice Sets the incentivizer contract */ event NewIncentivizer(address oldIncentivizer, address newIncentivizer); /** * @notice Sets the StakingPool contract */ event NewStakingPool(address oldStakingPool, address newStakingPool); /** * @notice Sets the TeamPool contract */ event NewTeamPool(address oldTeamPool, address newTeamPool); /** * @notice Sets the Dev contract */ event NewDev(address oldDev, address newDev); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); // Public functions function totalSupply() external view returns (uint256); function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function balanceOfUnderlying(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function maxScalingFactor() external view returns (uint256); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); function _setRebaser(address rebaser_) external; function _setIncentivizer(address incentivizer_) external; function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } contract GAMERGovernanceToken is GAMERTokenInterface { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GAMER::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "GAMER::delegateBySig: invalid nonce"); require(now <= expiry, "GAMER::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "GAMER::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = _gamerBalances[delegator]; // balance of underlying GAMERs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "GAMER::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } contract GAMERToken is GAMERGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov, 'not gov'); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } modifier onlyMinter() { require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == stakingPool || msg.sender == teamPool || msg.sender == dev || msg.sender == gov, "not minter"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(gamersScalingFactor == 0, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Computes the current totalSupply */ function totalSupply() external view returns (uint256) { return _totalSupply.div(10**24/ (BASE)); } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * gamersScalingFactor // this is used to check if gamersScalingFactor will be too high to compute balances when rebasing. return uint256(-1) / initSupply; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { // increase totalSupply _totalSupply = _totalSupply.add(amount.mul(10**24/ (BASE))); // get underlying value uint256 gamerValue = amount.mul(internalDecimals).div(gamersScalingFactor); // increase initSupply initSupply = initSupply.add(gamerValue); // make sure the mint didnt push maxScalingFactor too low require(gamersScalingFactor <= _maxScalingFactor(), "max scaling factor too low"); // add balance _gamerBalances[to] = _gamerBalances[to].add(gamerValue); emit Transfer(address(0), to, amount); // add delegates to the minter _moveDelegates(address(0), _delegates[to], gamerValue); emit Mint(to, amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // underlying balance is stored in gamers, so divide by current scaling factor // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == gamersScalingFactor / 1e24; // get amount in underlying uint256 gamerValue = value.mul(internalDecimals).div(gamersScalingFactor); // sub from balance of sender _gamerBalances[msg.sender] = _gamerBalances[msg.sender].sub(gamerValue); // add to balance of receiver _gamerBalances[to] = _gamerBalances[to].add(gamerValue); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], gamerValue); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); // get value in gamers uint256 gamerValue = value.mul(internalDecimals).div(gamersScalingFactor); // sub from from _gamerBalances[from] = _gamerBalances[from].sub(gamerValue); _gamerBalances[to] = _gamerBalances[to].add(gamerValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], gamerValue); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _gamerBalances[who].mul(gamersScalingFactor).div(internalDecimals); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external view returns (uint256) { return _gamerBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /* - Governance Functions - */ /** @notice sets the rebaser * @param rebaser_ The address of the rebaser contract to use for authentication. */ function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; rebaser = rebaser_; emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the incentivizer * @param incentivizer_ The address of the incentivizer contract to use for authentication. */ function _setIncentivizer(address incentivizer_) external onlyGov { address oldIncentivizer = incentivizer; incentivizer = incentivizer_; emit NewIncentivizer(oldIncentivizer, incentivizer_); } /** @notice sets the stakingPool * @param stakingPool_ The address of the stakingPool contract to use for authentication. */ function _setStakingPool(address stakingPool_) external onlyGov { address oldStakingPool = stakingPool; stakingPool = stakingPool_; emit NewStakingPool(oldStakingPool, stakingPool_); } /** @notice sets the teamPool * @param teamPool_ The address of the teamPool contract to use for authentication. */ function _setTeamPool(address teamPool_) external onlyGov { address oldTeamPool = teamPool; teamPool = teamPool_; emit NewTeamPool(oldTeamPool, teamPool_); } /** @notice sets the dev * @param dev_ The address of the dev contract to use for authentication. */ function _setDev(address dev_) external onlyGov { address oldDev = dev; dev = dev_; emit NewDev(oldDev, dev_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /* - Extras - */ /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external onlyRebaser returns (uint256) { if (indexDelta == 0) { emit Rebase(epoch, gamersScalingFactor, gamersScalingFactor); return _totalSupply; } uint256 prevGrapsScalingFactor = gamersScalingFactor; if (!positive) { gamersScalingFactor = gamersScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); } else { uint256 newScalingFactor = gamersScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { gamersScalingFactor = newScalingFactor; } else { gamersScalingFactor = _maxScalingFactor(); } } _totalSupply = initSupply.mul(gamersScalingFactor).div(BASE); emit Rebase(epoch, prevGrapsScalingFactor, gamersScalingFactor); return _totalSupply; } } contract GAMER is GAMERToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_ ) public { require(initSupply_ > 0, "0 init supply"); super.initialize(name_, symbol_, decimals_); initSupply = initSupply_.mul(10**24/ (BASE)); _totalSupply = initSupply; gamersScalingFactor = BASE; _gamerBalances[initial_owner] = initSupply_.mul(10**24 / (BASE)); // owner renounces ownership after deployment as they need to set // rebaser and incentivizer // gov = gov_; } }
0x608060405234801561001057600080fd5b50600436106100df5760003560e01c80634bda2e201161008c57806385ae33881161006657806385ae33881461024c57806393b8faf51461027f578063f4325d671461029c578063fa8f3455146102a4576100df565b80634bda2e20146101f757806373f03dff146101ff57806375172a8b14610232576100df565b806325240810116100bd57806325240810146101df578063463256ee146101e757806348df5829146101ef576100df565b8063078e9d53146100e457806311fd8a83146101a657806312d43a51146101d7575b600080fd5b6101a4600480360360408110156100fa57600080fd5b73ffffffffffffffffffffffffffffffffffffffff823516919081019060408101602082013564010000000081111561013257600080fd5b82018360208201111561014457600080fd5b8035906020019184602083028401116401000000008311171561016657600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506102d7945050505050565b005b6101ae6103e6565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b6101ae610402565b6101ae61041e565b6101ae61043a565b6101ae610456565b6101a4610472565b6101a46004803603602081101561021557600080fd5b503573ffffffffffffffffffffffffffffffffffffffff1661058b565b61023a610637565b60408051918252519081900360200190f35b6101a46004803603602081101561026257600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166106da565b6101a46004803603602081101561029557600080fd5b5035610786565b6101ae6108e6565b6101a4600480360360208110156102ba57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16610902565b60015473ffffffffffffffffffffffffffffffffffffffff1633146102fb57600080fd5b60005b81518110156103e157600082828151811061031557fe5b6020026020010151905060008173ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561039e57600080fd5b505afa1580156103b2573d6000803e3d6000fd5b505050506040513d60208110156103c857600080fd5b505190506103d7828683610b40565b50506001016102fe565b505050565b60035473ffffffffffffffffffffffffffffffffffffffff1681565b60015473ffffffffffffffffffffffffffffffffffffffff1681565b60025473ffffffffffffffffffffffffffffffffffffffff1681565b60045473ffffffffffffffffffffffffffffffffffffffff1681565b60055473ffffffffffffffffffffffffffffffffffffffff1681565b60025473ffffffffffffffffffffffffffffffffffffffff1633146104f857604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600860248201527f2170656e64696e67000000000000000000000000000000000000000000000000604482015290519081900360640190fd5b60018054600280547fffffffffffffffffffffffff000000000000000000000000000000000000000080841673ffffffffffffffffffffffffffffffffffffffff838116919091179586905591169091556040805192821680845293909116602083015280517f1f14cfc03e486d23acee577b07bc0b3b23f4888c91fcdba5e0fef5a2549d55239281900390910190a150565b60015473ffffffffffffffffffffffffffffffffffffffff1633146105af57600080fd5b6002805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681179093556040805191909216808252602082019390935281517f6163d5b9efd962645dd649e6e48a61bcb0f9df00997a2398b80d135a9ab0c61e929181900390910190a15050565b60008054604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b1580156106a957600080fd5b505afa1580156106bd573d6000803e3d6000fd5b505050506040513d60208110156106d357600080fd5b5051905090565b60015473ffffffffffffffffffffffffffffffffffffffff1633146106fe57600080fd5b6005805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681179093556040805191909216808252602082019390935281517f0bb0284e37319c3f2a212ac57257fcfb836298171986172ae5b764d335b174bf929181900390910190a15050565b60035473ffffffffffffffffffffffffffffffffffffffff1633146107aa57600080fd5b60008054600554604080517fa9059cbb00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9283166004820152602481018690529051919092169263a9059cbb92604480820193602093909283900390910190829087803b15801561082c57600080fd5b505af1158015610840573d6000803e3d6000fd5b505050506040513d602081101561085657600080fd5b5050600554604080517f927b1d2900000000000000000000000000000000000000000000000000000000815260048101849052905173ffffffffffffffffffffffffffffffffffffffff9092169163927b1d299160248082019260009290919082900301818387803b1580156108cb57600080fd5b505af11580156108df573d6000803e3d6000fd5b5050505050565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b60015473ffffffffffffffffffffffffffffffffffffffff16331461092657600080fd5b60035460048054604080517fa457c2d700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff9485169381018490527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6024820152905192939091169163a457c2d7916044808201926020929091908290030181600087803b1580156109c857600080fd5b505af11580156109dc573d6000803e3d6000fd5b505050506040513d60208110156109f257600080fd5b5050600380547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff84811691821790925560048054604080517f095ea7b3000000000000000000000000000000000000000000000000000000008152928301939093527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60248301529151919092169163095ea7b39160448083019260209291908290030181600087803b158015610abe57600080fd5b505af1158015610ad2573d6000803e3d6000fd5b505050506040513d6020811015610ae857600080fd5b50506040805173ffffffffffffffffffffffffffffffffffffffff80841682528416602082015281517f51f448520e2183de499e224808a409ee01a1f380edb2e8497572320c15030545929181900390910190a15050565b6040805173ffffffffffffffffffffffffffffffffffffffff8416602482015260448082018490528251808303909101815260649091019091526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001790526103e19084906060610c2a826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c65648152508573ffffffffffffffffffffffffffffffffffffffff16610ca09092919063ffffffff16565b8051909150156103e157808060200190516020811015610c4957600080fd5b50516103e1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180610ec8602a913960400191505060405180910390fd5b6060610caf8484600085610cb7565b949350505050565b6060610cc285610ec1565b610d2d57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b600060608673ffffffffffffffffffffffffffffffffffffffff1685876040518082805190602001908083835b60208310610d9757805182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe09092019160209182019101610d5a565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114610df9576040519150601f19603f3d011682016040523d82523d6000602084013e610dfe565b606091505b50915091508115610e12579150610caf9050565b805115610e225780518082602001fd5b836040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610e86578181015183820152602001610e6e565b50505050905090810190601f168015610eb35780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b3b15159056fe5361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a265627a7a7231582092180f6647226df741d7605d64088c6debe4bc48371f612ff32b97deff128ca664736f6c63430005110032
[ 4, 7, 9, 16, 5 ]
0x46292f6ba764e34f69774913eea2f626591cb1e9
pragma solidity 0.6.2; 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); } } } } 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract TrulyWorthless is ERC20 { constructor () public ERC20("Truly", "TWC") { _mint(msg.sender, 1000000000 * (10 ** uint256(decimals()))); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b6106778560405180606001604052806028815260200161102660289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161109760259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110736024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fde6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061104e6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fbb6023913960400191505060405180910390fd5b610cc3838383610fb5565b610d2e81604051806060016040528060268152602001611000602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610dc1816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f1a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610edf578082015181840152602081019050610ec4565b50505050905090810190601f168015610f0c5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fab576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220b4e75fa95b04d8680a65cc8dd6e7f1fdba06f7f145955d7252a2d886ef000dbd64736f6c63430006020033
[ 38 ]
0x462edaa6c1339f98bcb59582af782326603df5f2
pragma solidity 0.4.24; contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal 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(_value <= balances[msg.sender]); require(_to != address(0)); 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]; } } contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission 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; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } contract NTER is CappedToken { string public name = "NTerprise"; string public symbol = "NTER"; uint8 public decimals = 18; constructor( uint256 _cap ) public CappedToken( _cap ) { } }
0x6080604052600436106100fb5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305d2035b811461010057806306fdde0314610129578063095ea7b3146101b357806318160ddd146101d757806323b872dd146101fe578063313ce56714610228578063355274ea1461025357806340c10f1914610268578063661884631461028c57806370a08231146102b0578063715018a6146102d15780637d64bcb4146102e85780638da5cb5b146102fd57806395d89b411461032e578063a9059cbb14610343578063d73dd62314610367578063dd62ed3e1461038b578063f2fde38b146103b2575b600080fd5b34801561010c57600080fd5b506101156103d3565b604080519115158252519081900360200190f35b34801561013557600080fd5b5061013e6103f4565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610178578181015183820152602001610160565b50505050905090810190601f1680156101a55780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101bf57600080fd5b50610115600160a060020a0360043516602435610482565b3480156101e357600080fd5b506101ec6104e8565b60408051918252519081900360200190f35b34801561020a57600080fd5b50610115600160a060020a03600435811690602435166044356104ee565b34801561023457600080fd5b5061023d610663565b6040805160ff9092168252519081900360200190f35b34801561025f57600080fd5b506101ec61066c565b34801561027457600080fd5b50610115600160a060020a0360043516602435610672565b34801561029857600080fd5b50610115600160a060020a03600435166024356106a8565b3480156102bc57600080fd5b506101ec600160a060020a0360043516610797565b3480156102dd57600080fd5b506102e66107b2565b005b3480156102f457600080fd5b50610115610820565b34801561030957600080fd5b506103126108c6565b60408051600160a060020a039092168252519081900360200190f35b34801561033a57600080fd5b5061013e6108d5565b34801561034f57600080fd5b50610115600160a060020a0360043516602435610930565b34801561037357600080fd5b50610115600160a060020a0360043516602435610a0f565b34801561039757600080fd5b506101ec600160a060020a0360043581169060243516610aa8565b3480156103be57600080fd5b506102e6600160a060020a0360043516610ad3565b60035474010000000000000000000000000000000000000000900460ff1681565b6005805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561047a5780601f1061044f5761010080835404028352916020019161047a565b820191906000526020600020905b81548152906001019060200180831161045d57829003601f168201915b505050505081565b336000818152600260209081526040808320600160a060020a038716808552908352818420869055815186815291519394909390927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925928290030190a350600192915050565b60015490565b600160a060020a03831660009081526020819052604081205482111561051357600080fd5b600160a060020a038416600090815260026020908152604080832033845290915290205482111561054357600080fd5b600160a060020a038316151561055857600080fd5b600160a060020a038416600090815260208190526040902054610581908363ffffffff610af616565b600160a060020a0380861660009081526020819052604080822093909355908516815220546105b6908363ffffffff610b0816565b600160a060020a038085166000908152602081815260408083209490945591871681526002825282812033825290915220546105f8908363ffffffff610af616565b600160a060020a03808616600081815260026020908152604080832033845282529182902094909455805186815290519287169391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a35060019392505050565b60075460ff1681565b60045481565b600060045461068c83600154610b0890919063ffffffff16565b111561069757600080fd5b6106a18383610b1b565b9392505050565b336000908152600260209081526040808320600160a060020a03861684529091528120548083106106fc57336000908152600260209081526040808320600160a060020a0388168452909152812055610731565b61070c818463ffffffff610af616565b336000908152600260209081526040808320600160a060020a03891684529091529020555b336000818152600260209081526040808320600160a060020a0389168085529083529281902054815190815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35060019392505050565b600160a060020a031660009081526020819052604090205490565b600354600160a060020a031633146107c957600080fd5b600354604051600160a060020a03909116907ff8df31144d9c2f0f6b59d69b8b98abd5459d07f2742c4df920b25aae33c6482090600090a26003805473ffffffffffffffffffffffffffffffffffffffff19169055565b600354600090600160a060020a0316331461083a57600080fd5b60035474010000000000000000000000000000000000000000900460ff161561086257600080fd5b6003805474ff00000000000000000000000000000000000000001916740100000000000000000000000000000000000000001790556040517fae5184fba832cb2b1f702aca6117b8d265eaf03ad33eb133f19dde0f5920fa0890600090a150600190565b600354600160a060020a031681565b6006805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561047a5780601f1061044f5761010080835404028352916020019161047a565b3360009081526020819052604081205482111561094c57600080fd5b600160a060020a038316151561096157600080fd5b33600090815260208190526040902054610981908363ffffffff610af616565b3360009081526020819052604080822092909255600160a060020a038516815220546109b3908363ffffffff610b0816565b600160a060020a038416600081815260208181526040918290209390935580518581529051919233927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a350600192915050565b336000908152600260209081526040808320600160a060020a0386168452909152812054610a43908363ffffffff610b0816565b336000818152600260209081526040808320600160a060020a0389168085529083529281902085905580519485525191937f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929081900390910190a350600192915050565b600160a060020a03918216600090815260026020908152604080832093909416825291909152205490565b600354600160a060020a03163314610aea57600080fd5b610af381610c36565b50565b600082821115610b0257fe5b50900390565b81810182811015610b1557fe5b92915050565b600354600090600160a060020a03163314610b3557600080fd5b60035474010000000000000000000000000000000000000000900460ff1615610b5d57600080fd5b600154610b70908363ffffffff610b0816565b600155600160a060020a038316600090815260208190526040902054610b9c908363ffffffff610b0816565b600160a060020a03841660008181526020818152604091829020939093558051858152905191927f0f6798a560793a54c3bcfe86a93cde1e73087d944c0ea20544137d412139688592918290030190a2604080518381529051600160a060020a038516916000917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a350600192915050565b600160a060020a0381161515610c4b57600080fd5b600354604051600160a060020a038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a36003805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790555600a165627a7a723058206ddf3e5a41f9ea055d44548f77ca9989eef1f8d9b1b94ceaf1e6cdfa7e8394110029
[ 38 ]
0x4639cd8cd52ec1cf2e496a606ce28d8afb1c792f
pragma solidity 0.6.12; abstract contract ERC20Interface { function totalSupply() public virtual view returns (uint); function balanceOf(address tokenOwner) public virtual view returns (uint256 balance); function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining); function transfer(address to, uint256 tokens) public virtual returns (bool success); function approve(address spender, uint256 tokens) public virtual returns (bool success); function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } contract Owned { address payable public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } contract Token is ERC20Interface, Owned { using SafeMath for uint256; string public symbol = "BREE"; string public name = "CBDAO"; uint256 public decimals = 18; uint256 private maxCapSupply = 1e7 * 10**(decimals); // 10 million uint256 _totalSupply = 1530409 * 10 ** (decimals); // 1,530,409 address stakeFarmingContract; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { // mint _totalSupply amount of tokens and send to owner balances[owner] = balances[owner].add(_totalSupply); emit Transfer(address(0),owner, _totalSupply); } // ------------------------------------------------------------------------ // Set the STAKE_FARMING_CONTRACT // @required only owner // ------------------------------------------------------------------------ function SetStakeFarmingContract(address _address) external onlyOwner{ require(_address != address(0), "Invalid address"); stakeFarmingContract = _address; } // ------------------------------------------------------------------------ // Token Minting function // @params _amount expects the amount of tokens to be minted excluding the // required decimals // @params _beneficiary tokens will be sent to _beneficiary // @required only owner OR stakeFarmingContract // ------------------------------------------------------------------------ function MintTokens(uint256 _amount, address _beneficiary) public returns(bool){ require(msg.sender == stakeFarmingContract); require(_beneficiary != address(0), "Invalid address"); require(_totalSupply.add(_amount) <= maxCapSupply, "exceeds max cap supply 10 million"); _totalSupply = _totalSupply.add(_amount); // mint _amount tokens and keep inside contract balances[_beneficiary] = balances[_beneficiary].add(_amount); emit Transfer(address(0),_beneficiary, _amount); return true; } // ------------------------------------------------------------------------ // Burn the `_amount` amount of tokens from the calling `account` // @params _amount the amount of tokens to burn // ------------------------------------------------------------------------ function BurnTokens(uint256 _amount) external { _burn(_amount, msg.sender); } // ------------------------------------------------------------------------ // @dev Internal function that burns an amount of the token from a given account // @param _amount The amount that will be burnt // @param _account The tokens to burn from // ------------------------------------------------------------------------ function _burn(uint256 _amount, address _account) internal { require(balances[_account] >= _amount, "insufficient account balance"); _totalSupply = _totalSupply.sub(_amount); balances[_account] = balances[_account].sub(_amount); emit Transfer(_account, address(0), _amount); } /** ERC20Interface function's implementation **/ // ------------------------------------------------------------------------ // Get the total supply of the `token` // ------------------------------------------------------------------------ function totalSupply() public override view returns (uint256){ return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public override view returns (uint256 balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint256 tokens) public override returns (bool success) { // prevent transfer to 0x0, use burn instead require(address(to) != address(0)); require(balances[msg.sender] >= tokens ); require(balances[to].add(tokens) >= balances[to]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender,to,tokens); return true; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint256 tokens) public override returns (bool success){ require(tokens <= allowed[from][msg.sender]); //check allowance require(balances[from] >= tokens); require(from != address(0), "Invalid address"); require(to != address(0), "Invalid address"); balances[from] = balances[from].sub(tokens); balances[to] = balances[to].add(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); emit Transfer(from,to,tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public override view returns (uint256 remaining) { return allowed[tokenOwner][spender]; } /** * @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, allowed[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, allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @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"); allowed[owner][spender] = value; emit Approval(owner, spender, value); } }
0x608060405234801561001057600080fd5b50600436106101005760003560e01c80636f2e33b511610097578063a457c2d711610066578063a457c2d714610309578063a9059cbb14610335578063dd62ed3e14610361578063f2fde38b1461038f57610100565b80636f2e33b51461029157806370a08231146102b75780638da5cb5b146102dd57806395d89b411461030157610100565b80632cd3fd70116100d35780632cd3fd7014610212578063313ce5671461023157806339509351146102395780636a9c5acd1461026557610100565b806306fdde0314610105578063095ea7b31461018257806318160ddd146101c257806323b872dd146101dc575b600080fd5b61010d6103b5565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561014757818101518382015260200161012f565b50505050905090810190601f1680156101745780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101ae6004803603604081101561019857600080fd5b506001600160a01b038135169060200135610440565b604080519115158252519081900360200190f35b6101ca610456565b60408051918252519081900360200190f35b6101ae600480360360608110156101f257600080fd5b506001600160a01b0381358116916020810135909116906040013561045c565b61022f6004803603602081101561022857600080fd5b5035610634565b005b6101ca610641565b6101ae6004803603604081101561024f57600080fd5b506001600160a01b038135169060200135610647565b6101ae6004803603604081101561027b57600080fd5b50803590602001356001600160a01b0316610682565b61022f600480360360208110156102a757600080fd5b50356001600160a01b03166107b4565b6101ca600480360360208110156102cd57600080fd5b50356001600160a01b031661083a565b6102e5610855565b604080516001600160a01b039092168252519081900360200190f35b61010d610864565b6101ae6004803603604081101561031f57600080fd5b506001600160a01b0381351690602001356108be565b6101ae6004803603604081101561034b57600080fd5b506001600160a01b0381351690602001356108f4565b6101ca6004803603604081101561037757600080fd5b506001600160a01b03813581169160200135166109e5565b61022f600480360360208110156103a557600080fd5b50356001600160a01b0316610a10565b6002805460408051602060018416156101000260001901909316849004601f810184900484028201840190925281815292918301828280156104385780601f1061040d57610100808354040283529160200191610438565b820191906000526020600020905b81548152906001019060200180831161041b57829003601f168201915b505050505081565b600061044d338484610a88565b50600192915050565b60055490565b6001600160a01b038316600090815260086020908152604080832033845290915281205482111561048c57600080fd5b6001600160a01b0384166000908152600760205260409020548211156104b157600080fd5b6001600160a01b0384166104fe576040805162461bcd60e51b815260206004820152600f60248201526e496e76616c6964206164647265737360881b604482015290519081900360640190fd5b6001600160a01b03831661054b576040805162461bcd60e51b815260206004820152600f60248201526e496e76616c6964206164647265737360881b604482015290519081900360640190fd5b6001600160a01b03841660009081526007602052604090205461056e9083610b74565b6001600160a01b03808616600090815260076020526040808220939093559085168152205461059d9083610a72565b6001600160a01b0380851660009081526007602090815260408083209490945591871681526008825282812033825290915220546105db9083610b74565b6001600160a01b0380861660008181526008602090815260408083203384528252918290209490945580518681529051928716939192600080516020610caf833981519152929181900390910190a35060019392505050565b61063e8133610b86565b50565b60035481565b3360008181526008602090815260408083206001600160a01b0387168452909152812054909161044d91859061067d9086610a72565b610a88565b6006546000906001600160a01b0316331461069c57600080fd5b6001600160a01b0382166106e9576040805162461bcd60e51b815260206004820152600f60248201526e496e76616c6964206164647265737360881b604482015290519081900360640190fd5b6004546005546106f99085610a72565b11156107365760405162461bcd60e51b8152600401808060200182810382526021815260200180610c8e6021913960400191505060405180910390fd5b6005546107439084610a72565b6005556001600160a01b0382166000908152600760205260409020546107699084610a72565b6001600160a01b0383166000818152600760209081526040808320949094558351878152935192939192600080516020610caf8339815191529281900390910190a350600192915050565b6000546001600160a01b031633146107cb57600080fd5b6001600160a01b038116610818576040805162461bcd60e51b815260206004820152600f60248201526e496e76616c6964206164647265737360881b604482015290519081900360640190fd5b600680546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b031660009081526007602052604090205490565b6000546001600160a01b031681565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156104385780601f1061040d57610100808354040283529160200191610438565b3360008181526008602090815260408083206001600160a01b0387168452909152812054909161044d91859061067d9086610b74565b60006001600160a01b03831661090957600080fd5b3360009081526007602052604090205482111561092557600080fd5b6001600160a01b0383166000908152600760205260409020546109488184610a72565b101561095357600080fd5b3360009081526007602052604090205461096d9083610b74565b33600090815260076020526040808220929092556001600160a01b038516815220546109999083610a72565b6001600160a01b038416600081815260076020908152604091829020939093558051858152905191923392600080516020610caf8339815191529281900390910190a350600192915050565b6001600160a01b03918216600090815260086020908152604080832093909416825291909152205490565b6000546001600160a01b03163314610a2757600080fd5b600080546001600160a01b0319166001600160a01b0383169081178255604051909133917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a350565b600082820183811015610a8157fe5b9392505050565b6001600160a01b038316610acd5760405162461bcd60e51b8152600401808060200182810382526024815260200180610ccf6024913960400191505060405180910390fd5b6001600160a01b038216610b125760405162461bcd60e51b8152600401808060200182810382526022815260200180610c6c6022913960400191505060405180910390fd5b6001600160a01b03808416600081815260086020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600082821115610b8057fe5b50900390565b6001600160a01b038116600090815260076020526040902054821115610bf3576040805162461bcd60e51b815260206004820152601c60248201527f696e73756666696369656e74206163636f756e742062616c616e636500000000604482015290519081900360640190fd5b600554610c009083610b74565b6005556001600160a01b038116600090815260076020526040902054610c269083610b74565b6001600160a01b038216600081815260076020908152604080832094909455835186815293519193600080516020610caf833981519152929081900390910190a3505056fe45524332303a20617070726f766520746f20746865207a65726f206164647265737365786365656473206d61782063617020737570706c79203130206d696c6c696f6eddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef45524332303a20617070726f76652066726f6d20746865207a65726f2061646472657373a264697066735822122048fef6e581f8c0f4d6f38c82cf99ee06cefd120f0d8eb50bb3389359bf9a250164736f6c634300060c0033
[ 4 ]
0x464c84c41f3C25Ba5a75B006D8B20600A8777306
pragma solidity 0.7.4; interface IArbitrable { /** * @dev To be raised when a ruling is given. * @param _arbitrator The arbitrator giving the ruling. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _ruling The ruling which was given. */ event Ruling(IArbitrator indexed _arbitrator, uint256 indexed _disputeID, uint256 _ruling); /** * @dev Give 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 "Not able/wanting to make a decision". */ function rule(uint256 _disputeID, uint256 _ruling) external; } interface IArbitrator { enum DisputeStatus {Waiting, Appealable, Solved} /** * @dev To be emitted when a dispute is created. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event DisputeCreation(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev To be emitted when a dispute can be appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealPossible(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev To be emitted when the current ruling is appealed. * @param _disputeID ID of the dispute. * @param _arbitrable The contract which created the dispute. */ event AppealDecision(uint256 indexed _disputeID, IArbitrable indexed _arbitrable); /** * @dev Create a dispute. Must be called by the arbitrable contract. * Must be paid at least arbitrationCost(_extraData). * @param _choices Amount of choices the arbitrator can make in this dispute. * @param _extraData Can be used to give additional info on the dispute to be created. * @return disputeID ID of the dispute created. */ function createDispute(uint256 _choices, bytes calldata _extraData) external payable returns (uint256 disputeID); /** * @dev Compute the cost of arbitration. It is recommended not to increase it often, as it can be highly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function arbitrationCost(bytes calldata _extraData) external view returns (uint256 cost); /** * @dev Appeal a ruling. Note that it has to be called before the arbitrator contract calls rule. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give extra info on the appeal. */ function appeal(uint256 _disputeID, bytes calldata _extraData) external payable; /** * @dev Compute the cost of appeal. It is recommended not to increase it often, as it can be higly time and gas consuming for the arbitrated contracts to cope with fee augmentation. * @param _disputeID ID of the dispute to be appealed. * @param _extraData Can be used to give additional info on the dispute to be created. * @return cost Amount to be paid. */ function appealCost(uint256 _disputeID, bytes calldata _extraData) external view returns (uint256 cost); /** * @dev Compute the start and end of the dispute's current or next appeal period, if possible. If not known or appeal is impossible: should return (0, 0). * @param _disputeID ID of the dispute. * @return start The start of the period. * @return end The end of the period. */ function appealPeriod(uint256 _disputeID) external view returns (uint256 start, uint256 end); /** * @dev Return the status of a dispute. * @param _disputeID ID of the dispute to rule. * @return status The status of the dispute. */ function disputeStatus(uint256 _disputeID) external view returns (DisputeStatus status); /** * @dev Return the current ruling of a dispute. This is useful for parties to know if they should appeal. * @param _disputeID ID of the dispute. * @return ruling The ruling which has been given or the one which will be given if there is no appeal. */ function currentRuling(uint256 _disputeID) external view returns (uint256 ruling); } interface IEvidence { /** * @dev To be emitted when meta-evidence is submitted. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidence A link to the meta-evidence JSON. */ event MetaEvidence(uint256 indexed _metaEvidenceID, string _evidence); /** * @dev To be raised when evidence is submitted. Should point to the resource (evidences are not to be stored on chain due to gas considerations). * @param _arbitrator The arbitrator of the contract. * @param _evidenceGroupID Unique identifier of the evidence group the evidence belongs to. * @param _party The address of the party submiting the evidence. Note that 0x0 refers to evidence not submitted by any party. * @param _evidence A URI to the evidence JSON file whose name should be its keccak256 hash followed by .json. */ event Evidence( IArbitrator indexed _arbitrator, uint256 indexed _evidenceGroupID, address indexed _party, string _evidence ); /** * @dev To be emitted when a dispute is created to link the correct meta-evidence to the disputeID. * @param _arbitrator The arbitrator of the contract. * @param _disputeID ID of the dispute in the Arbitrator contract. * @param _metaEvidenceID Unique identifier of meta-evidence. * @param _evidenceGroupID Unique identifier of the evidence group that is linked to this dispute. */ event Dispute( IArbitrator indexed _arbitrator, uint256 indexed _disputeID, uint256 _metaEvidenceID, uint256 _evidenceGroupID ); } library CappedMath { uint constant private UINT_MAX = 2**256 - 1; /** * @dev Adds two unsigned integers, returns 2^256 - 1 on overflow. */ function addCap(uint _a, uint _b) internal pure returns (uint) { uint c = _a + _b; return c >= _a ? c : UINT_MAX; } /** * @dev Subtracts two integers, returns 0 on underflow. */ function subCap(uint _a, uint _b) internal pure returns (uint) { if (_b > _a) return 0; else return _a - _b; } /** * @dev Multiplies two unsigned integers, returns 2^256 - 1 on overflow. */ function mulCap(uint _a, uint _b) internal pure returns (uint) { // 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; uint c = _a * _b; return c / _a == _b ? c : UINT_MAX; } } 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; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { /** * @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) { // 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); } } } } contract Linguo is IArbitrable, IEvidence { using CappedMath for uint256; /* *** Contract variables *** */ uint8 public constant VERSION_ID = 0; // Value that represents the version of the contract. The value is incremented each time the new version is deployed. Range for LinguoETH: 0-127, LinguoToken: 128-255. uint256 public constant MULTIPLIER_DIVISOR = 10000; // Divisor parameter for multipliers. uint256 private constant NOT_PAYABLE_VALUE = (2**256 - 2) / 2; // A value depositors won't be able to pay. enum Status {Created, Assigned, AwaitingReview, DisputeCreated, Resolved} enum Party { None, // Party that is mapped with a 0 dispute ruling. Translator, // Party performing translation task. Challenger // Party challenging translated text in the review period. } // Arrays of 3 elements in the Task and Round structs map to the parties. Index "0" is not used, "1" is used for the translator and "2" for the challenger. struct Task { uint256 submissionTimeout; // Time in seconds allotted for submitting a translation. The end of this period is considered a deadline. uint256 minPrice; // Minimum price for the translation. When the task is created it has this minimum price that gradually increases such that it reaches the maximum price at the deadline. uint256 maxPrice; // Maximum price for the translation and also the value that must be deposited by the requester. Status status; // Status of the task. uint256 lastInteraction; // The time of the last action performed on the task. Note that lastInteraction is updated only during timeout-related actions such as the creation of the task and the submission of the translation. address payable requester; // The party requesting the translation. uint256 requesterDeposit; // The deposit requester makes when creating the task. Once the task is assigned this deposit will be partially reimbursed and its value replaced by the task price. uint256 sumDeposit; // The sum of the deposits of the translator and the challenger, if any. This value (minus arbitration fees) will be paid to the party that wins the dispute. address payable[3] parties; // Translator and challenger of the task. uint256 disputeID; // The ID of the dispute created in the arbitrator contract. Round[] rounds; // Tracks each appeal round of a dispute. uint256 ruling; // Ruling given to the dispute of the task by the arbitrator. } struct Round { uint256[3] paidFees; // Tracks the fees paid by each side in this round. bool[3] hasPaid; // True when the side has fully paid its fee. False otherwise. uint256 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 => uint256[3]) contributions; // Maps contributors to their contributions for each side. } address public governor = msg.sender; // The governor of the contract. IArbitrator public immutable arbitrator; // The address of the ERC-792 Arbitrator. bytes public arbitratorExtraData; // Extra data to allow creating a dispute on the arbitrator. uint256 public reviewTimeout; // Time in seconds, during which the submitted translation can be challenged. // All multipliers below are in basis points. uint256 public translationMultiplier; // Multiplier for calculating the value of the deposit translator must pay to self-assign a task. uint256 public challengeMultiplier; // Multiplier for calculating the value of the deposit challenger must pay to challenge a translation. uint256 public sharedStakeMultiplier; // Multiplier for calculating the appeal fee that must be paid by the submitter in the case where there isn't a winner and loser (e.g. when the arbitrator ruled "refuse to arbitrate"). uint256 public winnerStakeMultiplier; // Multiplier for calculating the appeal fee of the party that won the previous round. uint256 public loserStakeMultiplier; // Multiplier for calculating the appeal fee of the party that lost the previous round. Task[] public tasks; // Stores all created tasks. mapping(uint256 => uint256) public disputeIDtoTaskID; // Maps a disputeID to its respective task. /* *** Events *** */ /** @dev To be emitted when a new task is created. * @param _taskID The ID of the newly created task. * @param _requester The address that created the task. * @param _timestamp When the task was created. */ event TaskCreated(uint256 indexed _taskID, address indexed _requester, uint256 _timestamp); /** @dev To be emitted when a translator assigns a task to himself. * @param _taskID The ID of the assigned task. * @param _translator The address that was assigned to the task. * @param _price The task price at the moment it was assigned. * @param _timestamp When the task was assigned. */ event TaskAssigned(uint256 indexed _taskID, address indexed _translator, uint256 _price, uint256 _timestamp); /** @dev To be emitted when a translation is submitted. * @param _taskID The ID of the respective task. * @param _translator The address that performed the translation. * @param _translatedText A URI to the translated text. * @param _timestamp When the translation was submitted. */ event TranslationSubmitted( uint256 indexed _taskID, address indexed _translator, string _translatedText, uint256 _timestamp ); /** @dev To be emitted when a translation is challenged. * @param _taskID The ID of the respective task. * @param _challenger The address of the challenger. * @param _timestamp When the task was challenged. */ event TranslationChallenged(uint256 indexed _taskID, address indexed _challenger, uint256 _timestamp); /** @dev To be emitted when a task is resolved, either by the translation being accepted, the requester being reimbursed or a dispute being settled. * @param _taskID The ID of the respective task. * @param _reason Short description of what caused the task to be solved. One of: 'translation-accepted' | 'requester-reimbursed' | 'dispute-settled' * @param _timestamp When the task was resolved. */ event TaskResolved(uint256 indexed _taskID, string _reason, uint256 _timestamp); /** @dev To be emitted when someone contributes to the appeal process. * @param _taskID The ID of the respective task. * @param _party The party which received the contribution. * @param _contributor The address of the contributor. * @param _amount The amount contributed. */ event AppealContribution(uint256 indexed _taskID, Party _party, address indexed _contributor, uint256 _amount); /** @dev To be emitted when the appeal fees of one of the parties are fully funded. * @param _taskID The ID of the respective task. * @param _party The party that is fully funded. */ event HasPaidAppealFee(uint256 indexed _taskID, Party _party); /* *** Modifiers *** */ modifier onlyGovernor() { require(msg.sender == governor, "Only governor is allowed to perform this."); _; } /** @dev Constructor. * @param _arbitrator The arbitrator of the contract. * @param _arbitratorExtraData Extra data for the arbitrator. * @param _reviewTimeout Time in seconds during which a translation can be challenged. * @param _translationMultiplier Multiplier for calculating translator's deposit. In basis points. * @param _challengeMultiplier Multiplier for calculating challenger's deposit. In basis points. * @param _sharedStakeMultiplier Multiplier of the appeal cost that submitter must pay for a round when there is no winner/loser in the previous round. In basis points. * @param _winnerStakeMultiplier Multiplier of the appeal cost that the winner has to pay for a round. In basis points. * @param _loserStakeMultiplier Multiplier of the appeal cost that the loser has to pay for a round. In basis points. */ constructor( IArbitrator _arbitrator, bytes memory _arbitratorExtraData, uint256 _reviewTimeout, uint256 _translationMultiplier, uint256 _challengeMultiplier, uint256 _sharedStakeMultiplier, uint256 _winnerStakeMultiplier, uint256 _loserStakeMultiplier ) public { arbitrator = _arbitrator; arbitratorExtraData = _arbitratorExtraData; reviewTimeout = _reviewTimeout; translationMultiplier = _translationMultiplier; challengeMultiplier = _challengeMultiplier; sharedStakeMultiplier = _sharedStakeMultiplier; winnerStakeMultiplier = _winnerStakeMultiplier; loserStakeMultiplier = _loserStakeMultiplier; } // ******************** // // * Governance * // // ******************** // /** @dev Changes the governor of this contract. * @param _governor A new governor. */ function changeGovernor(address _governor) public onlyGovernor { governor = _governor; } /** @dev Changes the time allocated for the review phase. * @param _reviewTimeout A new value of the time allotted for reviewing a translation. In seconds. */ function changeReviewTimeout(uint256 _reviewTimeout) public onlyGovernor { reviewTimeout = _reviewTimeout; } /** @dev Changes the multiplier for translators' deposit. * @param _translationMultiplier A new value of the multiplier for calculating translator's deposit. In basis points. */ function changeTranslationMultiplier(uint256 _translationMultiplier) public onlyGovernor { translationMultiplier = _translationMultiplier; } /** @dev Changes the multiplier for challengers' deposit. * @param _challengeMultiplier A new value of the multiplier for calculating challenger's deposit. In basis points. */ function changeChallengeMultiplier(uint256 _challengeMultiplier) public onlyGovernor { challengeMultiplier = _challengeMultiplier; } /** @dev Changes the percentage of arbitration fees that must be paid by parties as a fee stake if there was no winner and loser in the previous round. * @param _sharedStakeMultiplier A new value of the multiplier of the appeal cost in case where there was no winner/loser in previous round. In basis point. */ function changeSharedStakeMultiplier(uint256 _sharedStakeMultiplier) public onlyGovernor { sharedStakeMultiplier = _sharedStakeMultiplier; } /** @dev Changes the percentage of arbitration fees that must be paid as a fee stake by the party that won the previous round. * @param _winnerStakeMultiplier A new value of the multiplier of the appeal cost that the winner of the previous round has to pay. In basis points. */ function changeWinnerStakeMultiplier(uint256 _winnerStakeMultiplier) public onlyGovernor { winnerStakeMultiplier = _winnerStakeMultiplier; } /** @dev Changes the percentage of arbitration fees that must be paid as a fee stake by the party that lost the previous round. * @param _loserStakeMultiplier A new value for the multiplier of the appeal cost that the party that lost the previous round has to pay. In basis points. */ function changeLoserStakeMultiplier(uint256 _loserStakeMultiplier) public onlyGovernor { loserStakeMultiplier = _loserStakeMultiplier; } // **************************** // // * Modifying the state * // // **************************** // /** @dev Creates a task based on provided details. Requires a value of maximum price to be deposited. * @param _deadline The deadline for the translation to be completed. * @param _minPrice A minimum price of the translation. In wei. * @param _metaEvidence A URI of a meta-evidence object for task submission. * @return taskID The ID of the created task. */ function createTask( uint256 _deadline, uint256 _minPrice, string calldata _metaEvidence ) external payable returns (uint256 taskID) { require(msg.value >= _minPrice, "Deposited value should be greater than or equal to the min price."); require(_deadline > block.timestamp, "The deadline should be in the future."); taskID = tasks.length; Task storage task = tasks.push(); task.submissionTimeout = _deadline - block.timestamp; task.minPrice = _minPrice; task.maxPrice = msg.value; task.lastInteraction = block.timestamp; task.requester = msg.sender; task.requesterDeposit = msg.value; emit MetaEvidence(taskID, _metaEvidence); emit TaskCreated(taskID, msg.sender, block.timestamp); } /** @dev Assigns a specific task to the sender. Requires a translator's deposit. * Note that the deposit should be a little higher than the required value because of the price increase during the time the transaction is mined. The surplus will be reimbursed. * @param _taskID The ID of the task. */ function assignTask(uint256 _taskID) external payable { Task storage task = tasks[_taskID]; require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 translatorDeposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); require(task.status == Status.Created, "Task has already been assigned or reimbursed."); require(msg.value >= translatorDeposit, "Not enough ETH to reach the required deposit value."); task.parties[uint256(Party.Translator)] = msg.sender; task.status = Status.Assigned; uint256 remainder = task.maxPrice - price; task.requester.send(remainder); // Update requester's deposit since we reimbursed him the difference between maximum and actual price. task.requesterDeposit = price; task.sumDeposit = translatorDeposit; remainder = msg.value - translatorDeposit; msg.sender.send(remainder); emit TaskAssigned(_taskID, msg.sender, price, block.timestamp); } /** @dev Submits translated text for a specific task. * @param _taskID The ID of the task. * @param _translation A URI to the translated text. */ function submitTranslation(uint256 _taskID, string calldata _translation) external { Task storage task = tasks[_taskID]; require( task.status == Status.Assigned, "The task is either not assigned or translation has already been submitted." ); require(block.timestamp - task.lastInteraction <= task.submissionTimeout, "The deadline has already passed."); require( msg.sender == task.parties[uint256(Party.Translator)], "Can't submit translation to a task that wasn't assigned to you." ); task.status = Status.AwaitingReview; task.lastInteraction = block.timestamp; emit TranslationSubmitted(_taskID, msg.sender, _translation, block.timestamp); } /** @dev Reimburses the requester if no one picked the task or the translator failed to submit the translation before deadline. * @param _taskID The ID of the task. */ function reimburseRequester(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status < Status.AwaitingReview, "Can't reimburse if translation was submitted."); require( block.timestamp - task.lastInteraction > task.submissionTimeout, "Can't reimburse if the deadline hasn't passed yet." ); task.status = Status.Resolved; // Requester gets his deposit back and also the deposit of the translator, if there was one. // Note that sumDeposit can't contain challenger's deposit until the task is in DisputeCreated status. uint256 amount = task.requesterDeposit + task.sumDeposit; task.requester.send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "requester-reimbursed", block.timestamp); } /** @dev Pays the translator for completed task if no one challenged the translation during the review period. * @param _taskID The ID of the task. */ function acceptTranslation(uint256 _taskID) external { Task storage task = tasks[_taskID]; require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction > reviewTimeout, "The review phase hasn't passed yet."); task.status = Status.Resolved; // Translator gets the price of the task and his deposit back. Note that sumDeposit can't contain challenger's deposit until the task has DisputeCreated status. uint256 amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(_taskID, "translation-accepted", block.timestamp); } /** @dev Challenges the translation of a specific task. Requires challenger's deposit. * @param _taskID The ID of the task. * @param _evidence A link to evidence using its URI. Ignored if not provided. */ function challengeTranslation(uint256 _taskID, string calldata _evidence) external payable { Task storage task = tasks[_taskID]; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); uint256 challengeDeposit = arbitrationCost.addCap( (challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR ); require(task.status == Status.AwaitingReview, "The task is in the wrong status."); require(block.timestamp - task.lastInteraction <= reviewTimeout, "The review phase has already passed."); require(msg.value >= challengeDeposit, "Not enough ETH to cover challenge deposit."); task.status = Status.DisputeCreated; task.parties[uint256(Party.Challenger)] = msg.sender; task.disputeID = arbitrator.createDispute{value: arbitrationCost}(2, arbitratorExtraData); disputeIDtoTaskID[task.disputeID] = _taskID; task.rounds.push(); task.sumDeposit = task.sumDeposit.addCap(challengeDeposit).subCap(arbitrationCost); uint256 remainder = msg.value - challengeDeposit; msg.sender.send(remainder); emit Dispute(arbitrator, task.disputeID, _taskID, _taskID); emit TranslationChallenged(_taskID, msg.sender, block.timestamp); if (bytes(_evidence).length > 0) emit Evidence(arbitrator, _taskID, msg.sender, _evidence); } /** @dev Takes up to the total amount required to fund a side of an appeal. Reimburses the rest. Creates an appeal if all sides are fully funded. * @param _taskID The ID of challenged task. * @param _side The party that pays the appeal fee. */ function fundAppeal(uint256 _taskID, Party _side) external payable { Task storage task = tasks[_taskID]; require( _side == Party.Translator || _side == Party.Challenger, "Recipient must be either the translator or challenger." ); require(task.status == Status.DisputeCreated, "No dispute to appeal."); require( arbitrator.disputeStatus(task.disputeID) == IArbitrator.DisputeStatus.Appealable, "Dispute is not appealable." ); (uint256 appealPeriodStart, uint256 appealPeriodEnd) = arbitrator.appealPeriod(task.disputeID); require( block.timestamp >= appealPeriodStart && block.timestamp < appealPeriodEnd, "Funding must be made within the appeal period." ); uint256 winner = arbitrator.currentRuling(task.disputeID); uint256 multiplier; if (winner == uint256(_side)) { multiplier = winnerStakeMultiplier; } else if (winner == 0) { multiplier = sharedStakeMultiplier; } else { require( block.timestamp - appealPeriodStart < (appealPeriodEnd - appealPeriodStart) / 2, "The loser must pay during the first half of the appeal period." ); multiplier = loserStakeMultiplier; } Round storage round = task.rounds[task.rounds.length - 1]; require(!round.hasPaid[uint256(_side)], "Appeal fee has already been paid."); uint256 appealCost = arbitrator.appealCost(task.disputeID, arbitratorExtraData); uint256 totalCost = appealCost.addCap((appealCost.mulCap(multiplier)) / MULTIPLIER_DIVISOR); // Take up to the amount necessary to fund the current round at the current costs. uint256 contribution; // Amount contributed. uint256 remainingETH; // Remaining ETH to send back. (contribution, remainingETH) = calculateContribution( msg.value, totalCost.subCap(round.paidFees[uint256(_side)]) ); round.contributions[msg.sender][uint256(_side)] += contribution; round.paidFees[uint256(_side)] += contribution; emit AppealContribution(_taskID, _side, msg.sender, contribution); // Add contribution to reward when the fee funding is successful, otherwise it can be withdrawn later. if (round.paidFees[uint256(_side)] >= totalCost) { round.hasPaid[uint256(_side)] = true; round.feeRewards += round.paidFees[uint256(_side)]; emit HasPaidAppealFee(_taskID, _side); } // Reimburse leftover ETH. msg.sender.send(remainingETH); // Deliberate use of send in order to not block the contract in case of reverting fallback. // Create an appeal if each side is funded. if (round.hasPaid[uint256(Party.Translator)] && round.hasPaid[uint256(Party.Challenger)]) { arbitrator.appeal{value: appealCost}(task.disputeID, arbitratorExtraData); task.rounds.push(); round.feeRewards = round.feeRewards.subCap(appealCost); } } /** @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(uint256 _available, uint256 _requiredAmount) internal pure returns (uint256 taken, uint256 remainder) { if (_requiredAmount > _available) return (_available, 0); // Take whatever is available, return 0 as leftover ETH. remainder = _available - _requiredAmount; return (_requiredAmount, remainder); } /** @dev Withdraws contributions of appeal rounds. Reimburses contributions if no disputes were raised. If a dispute was raised, sends the fee stake rewards and reimbursements proportional to the contributions made to the winner of a dispute. * @param _beneficiary The address that made contributions. * @param _taskID The ID of the associated task. * @param _round The round from which to withdraw. */ function withdrawFeesAndRewards( address payable _beneficiary, uint256 _taskID, uint256 _round ) public { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; require(task.status == Status.Resolved, "The task should be resolved."); uint256 reward; if (!round.hasPaid[uint256(Party.Translator)] || !round.hasPaid[uint256(Party.Challenger)]) { // Allow to reimburse if funding was unsuccessful. reward = round.contributions[_beneficiary][uint256(Party.Translator)] + round.contributions[_beneficiary][uint256(Party.Challenger)]; round.contributions[_beneficiary][uint256(Party.Translator)] = 0; round.contributions[_beneficiary][uint256(Party.Challenger)] = 0; } else if (task.ruling == uint256(Party.None)) { // Reimburse unspent fees proportionally if there is no winner and loser. uint256 rewardTranslator = round.paidFees[uint256(Party.Translator)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Translator)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; uint256 rewardChallenger = round.paidFees[uint256(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; reward = rewardTranslator + rewardChallenger; round.contributions[_beneficiary][uint256(Party.Translator)] = 0; round.contributions[_beneficiary][uint256(Party.Challenger)] = 0; } else { // Reward the winner. reward = round.paidFees[task.ruling] > 0 ? (round.contributions[_beneficiary][task.ruling] * round.feeRewards) / round.paidFees[task.ruling] : 0; round.contributions[_beneficiary][task.ruling] = 0; } _beneficiary.send(reward); // It is the user's responsibility to accept ETH. } /** @dev Withdraws contributions of multiple appeal rounds at once. This function is O(n) where n is the number of rounds. This could exceed the gas limit, therefore this function should be used only as a utility and not be relied upon by other contracts. * @param _beneficiary The address that made contributions. * @param _taskID The ID of the associated task. * @param _cursor The round from where to start withdrawing. * @param _count The number of rounds to iterate. If set to 0 or a value larger than the number of rounds, iterates until the last round. */ function batchRoundWithdraw( address payable _beneficiary, uint256 _taskID, uint256 _cursor, uint256 _count ) public { Task storage task = tasks[_taskID]; for (uint256 i = _cursor; i < task.rounds.length && (_count == 0 || i < _cursor + _count); i++) withdrawFeesAndRewards(_beneficiary, _taskID, i); } /** @dev Gives the ruling for a dispute. Can only 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 and to invert the ruling in the case a party loses from lack of appeal fees funding. * @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(uint256 _disputeID, uint256 _ruling) external override { Party resultRuling = Party(_ruling); uint256 taskID = disputeIDtoTaskID[_disputeID]; Task storage task = tasks[taskID]; Round storage round = task.rounds[task.rounds.length - 1]; require(msg.sender == address(arbitrator), "Must be called by the arbitrator."); require(task.status == Status.DisputeCreated, "The dispute has already been resolved."); // If only one side paid its fees we assume the ruling to be in its favor. if (round.hasPaid[uint256(Party.Translator)] == true) resultRuling = Party.Translator; else if (round.hasPaid[uint256(Party.Challenger)] == true) resultRuling = Party.Challenger; emit Ruling(IArbitrator(msg.sender), _disputeID, uint256(resultRuling)); executeRuling(_disputeID, uint256(resultRuling)); } /** @dev Executes the ruling of a dispute. * @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 executeRuling(uint256 _disputeID, uint256 _ruling) internal { uint256 taskID = disputeIDtoTaskID[_disputeID]; Task storage task = tasks[taskID]; task.status = Status.Resolved; task.ruling = _ruling; uint256 amount; if (_ruling == uint256(Party.None)) { task.requester.send(task.requesterDeposit); // The value of sumDeposit is split among parties in this case. If the sum is uneven the value of 1 wei can be burnt. amount = task.sumDeposit / 2; task.parties[uint256(Party.Translator)].send(amount); task.parties[uint256(Party.Challenger)].send(amount); } else if (_ruling == uint256(Party.Translator)) { amount = task.requesterDeposit + task.sumDeposit; task.parties[uint256(Party.Translator)].send(amount); } else { task.requester.send(task.requesterDeposit); task.parties[uint256(Party.Challenger)].send(task.sumDeposit); } task.requesterDeposit = 0; task.sumDeposit = 0; emit TaskResolved(taskID, "dispute-settled", block.timestamp); } /** @dev Submit a reference to evidence. EVENT. * @param _taskID The ID of the task. * @param _evidence A link to evidence using its URI. */ function submitEvidence(uint256 _taskID, string calldata _evidence) external { Task storage task = tasks[_taskID]; require(task.status != Status.Resolved, "The task must not already be resolved."); emit Evidence(arbitrator, _taskID, msg.sender, _evidence); } // ******************** // // * Getters * // // ******************** // /** @dev Returns the sum of withdrawable wei from appeal rounds. This function is O(n), where n is the number of rounds of the task. This could exceed the gas limit, therefore this function should only be used for interface display and not by other contracts. * @param _taskID The ID of the associated task. * @param _beneficiary The contributor for which to query. * @return total The total amount of wei available to withdraw. */ function amountWithdrawable(uint256 _taskID, address payable _beneficiary) external view returns (uint256 total) { Task storage task = tasks[_taskID]; if (task.status != Status.Resolved) return total; for (uint256 i = 0; i < task.rounds.length; i++) { Round storage round = task.rounds[i]; if (!round.hasPaid[uint256(Party.Translator)] || !round.hasPaid[uint256(Party.Challenger)]) { total += round.contributions[_beneficiary][uint256(Party.Translator)] + round.contributions[_beneficiary][uint256(Party.Challenger)]; } else if (task.ruling == uint256(Party.None)) { uint256 rewardTranslator = round.paidFees[uint256(Party.Translator)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Translator)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; uint256 rewardChallenger = round.paidFees[uint256(Party.Challenger)] > 0 ? (round.contributions[_beneficiary][uint256(Party.Challenger)] * round.feeRewards) / (round.paidFees[uint256(Party.Translator)] + round.paidFees[uint256(Party.Challenger)]) : 0; total += rewardTranslator + rewardChallenger; } else { total += round.paidFees[uint256(task.ruling)] > 0 ? (round.contributions[_beneficiary][uint256(task.ruling)] * round.feeRewards) / round.paidFees[uint256(task.ruling)] : 0; } } return total; } /** @dev Gets the deposit required for self-assigning the task. * @param _taskID The ID of the task. * @return deposit The translator's deposit. */ function getDepositValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { deposit = NOT_PAYABLE_VALUE; } else { uint256 price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); deposit = arbitrationCost.addCap((translationMultiplier.mulCap(price)) / MULTIPLIER_DIVISOR); } } /** @dev Gets the deposit required for challenging the translation. * @param _taskID The ID of the task. * @return deposit The challengers's deposit. */ function getChallengeValue(uint256 _taskID) public view returns (uint256 deposit) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > reviewTimeout || task.status != Status.AwaitingReview) { deposit = NOT_PAYABLE_VALUE; } else { uint256 arbitrationCost = arbitrator.arbitrationCost(arbitratorExtraData); deposit = arbitrationCost.addCap((challengeMultiplier.mulCap(task.requesterDeposit)) / MULTIPLIER_DIVISOR); } } /** @dev Gets the current price of a specified task. * @param _taskID The ID of the task. * @return price The price of the task. */ function getTaskPrice(uint256 _taskID) public view returns (uint256 price) { Task storage task = tasks[_taskID]; if (block.timestamp - task.lastInteraction > task.submissionTimeout || task.status != Status.Created) { price = 0; } else { price = task.minPrice + ((task.maxPrice - task.minPrice) * (block.timestamp - task.lastInteraction)) / task.submissionTimeout; } } /** @dev Gets the total number of created tasks. * @return The number of created tasks. */ function getTaskCount() public view returns (uint256) { return tasks.length; } /** @dev Gets the number of rounds of the specific task. * @param _taskID The ID of the task. * @return The number of rounds. */ function getNumberOfRounds(uint256 _taskID) public view returns (uint256) { Task storage task = tasks[_taskID]; return task.rounds.length; } /** @dev Gets the contributions made by a party for a given round of appeal of a task. * @param _taskID The ID of the task. * @param _round The position of the round. * @param _contributor The address of the contributor. * @return contributions The contributions. */ function getContributions( uint256 _taskID, uint256 _round, address _contributor ) public view returns (uint256[3] memory contributions) { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; contributions = round.contributions[_contributor]; } /** @dev Gets the addresses of parties of a specified task. * @param _taskID The ID of the task. * @return parties The addresses of translator and challenger as [ZERO_ADDRESS, translator, challenger]. */ function getTaskParties(uint256 _taskID) public view returns (address payable[3] memory parties) { Task storage task = tasks[_taskID]; parties = task.parties; } /** @dev Gets the information on a round of a task. * @param _taskID The ID of the task. * @param _round The round to be queried. * @return paidFees The amount paid by each party in the round. * @return hasPaid Whether or not a given party has paid the full fees for the round. * @return feeRewards The amount of fees that will be available as rewards for the winner. */ function getRoundInfo(uint256 _taskID, uint256 _round) public view returns ( uint256[3] memory paidFees, bool[3] memory hasPaid, uint256 feeRewards ) { Task storage task = tasks[_taskID]; Round storage round = task.rounds[_round]; return (round.paidFees, round.hasPaid, round.feeRewards); } } 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } 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); } } contract ERC20Mock is ERC20, ERC20Burnable { constructor(address initialAccount, uint256 initialBalance) ERC20("MockToken", "MCT") { _mint(initialAccount, initialBalance); } }
0x60806040526004361061023b5760003560e01c806382b350171161012e578063b5f3918b116100ab578063cc7b9d061161006f578063cc7b9d0614610a77578063d2dbe1d814610aa2578063d661dd3114610acc578063e4c0aaf414610ae1578063fc6f8f1614610b145761023b565b8063b5f3918b14610984578063b8573185146109ae578063c17a340e146109cb578063c36cd196146109e0578063c4e690df14610a625761023b565b806395c95522116100f257806395c955221461085a578063a6a7f0eb14610884578063a95c980514610906578063aba4ab7414610930578063adc7faba1461095a5761023b565b806382b3501714610613578063881f7c571461068d5780638a9bb02a146107025780638d9776721461079d57806392239dff146108305761023b565b8063244772e8116101bc57806368c76ffd1161018057806368c76ffd146105095780636cc6cde1146105805780636e8218aa146105955780636e99a23a146105bf5780637b943383146105fe5761023b565b8063244772e814610440578063311a6c561461046a578063339ac67c1461049a5780633a2dabfa146104df57806341658341146104f45761023b565b806312b3a2c01161020357806312b3a2c01461039c57806312ce3525146103c25780631972483a146103ec5780631d5120851461041657806320c58ca51461042b5761023b565b8063064ba1891461024057806309e24ad41461027c5780630c340a24146102a85780630c7ac7b6146102d95780631165542b14610363575b600080fd5b34801561024c57600080fd5b5061026a6004803603602081101561026357600080fd5b5035610b3e565b60408051918252519081900360200190f35b34801561028857600080fd5b506102a66004803603602081101561029f57600080fd5b5035610b50565b005b3480156102b457600080fd5b506102bd610b9e565b604080516001600160a01b039092168252519081900360200190f35b3480156102e557600080fd5b506102ee610bad565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610328578181015183820152602001610310565b50505050905090810190601f1680156103555780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561036f57600080fd5b5061026a6004803603604081101561038657600080fd5b50803590602001356001600160a01b0316610c3a565b6102a6600480360360408110156103b257600080fd5b508035906020013560ff16610e4a565b3480156103ce57600080fd5b506102a6600480360360208110156103e557600080fd5b50356116fb565b3480156103f857600080fd5b5061026a6004803603602081101561040f57600080fd5b5035611749565b34801561042257600080fd5b5061026a6118e8565b34801561043757600080fd5b5061026a6118ee565b34801561044c57600080fd5b5061026a6004803603602081101561046357600080fd5b50356118f4565b34801561047657600080fd5b506102a66004803603604081101561048d57600080fd5b508035906020013561197b565b3480156104a657600080fd5b506102a6600480360360808110156104bd57600080fd5b506001600160a01b038135169060208101359060408101359060600135611b3e565b3480156104eb57600080fd5b5061026a611b97565b34801561050057600080fd5b5061026a611b9d565b34801561051557600080fd5b506105486004803603606081101561052c57600080fd5b50803590602081013590604001356001600160a01b0316611ba3565b6040518082606080838360005b8381101561056d578181015183820152602001610555565b5050505090500191505060405180910390f35b34801561058c57600080fd5b506102bd611c3f565b3480156105a157600080fd5b5061026a600480360360208110156105b857600080fd5b5035611c63565b3480156105cb57600080fd5b506102a6600480360360608110156105e257600080fd5b506001600160a01b038135169060208101359060400135611e1a565b34801561060a57600080fd5b5061026a6120cf565b61026a6004803603606081101561062957600080fd5b813591602081013591810190606081016040820135600160201b81111561064f57600080fd5b82018360208201111561066157600080fd5b803590602001918460018302840111600160201b8311171561068257600080fd5b5090925090506120d5565b6102a6600480360360408110156106a357600080fd5b81359190810190604081016020820135600160201b8111156106c457600080fd5b8201836020820111156106d657600080fd5b803590602001918460018302840111600160201b831117156106f757600080fd5b509092509050612302565b34801561070e57600080fd5b506107326004803603604081101561072557600080fd5b508035906020013561281c565b6040518084606080838360005b8381101561075757818101518382015260200161073f565b5050505090500183600360200280838360005b8381101561078257818101518382015260200161076a565b50505050905001828152602001935050505060405180910390f35b3480156107a957600080fd5b506107c7600480360360208110156107c057600080fd5b5035612917565b604051808b81526020018a81526020018981526020018860048111156107e957fe5b8152602001878152602001866001600160a01b031681526020018581526020018481526020018381526020018281526020019a505050505050505050505060405180910390f35b34801561083c57600080fd5b506102a66004803603602081101561085357600080fd5b5035612989565b34801561086657600080fd5b506105486004803603602081101561087d57600080fd5b50356129d7565b34801561089057600080fd5b506102a6600480360360408110156108a757600080fd5b81359190810190604081016020820135600160201b8111156108c857600080fd5b8201836020820111156108da57600080fd5b803590602001918460018302840111600160201b831117156108fb57600080fd5b509092509050612a43565b34801561091257600080fd5b506102a66004803603602081101561092957600080fd5b5035612b51565b34801561093c57600080fd5b506102a66004803603602081101561095357600080fd5b5035612b9f565b34801561096657600080fd5b506102a66004803603602081101561097d57600080fd5b5035612d0e565b34801561099057600080fd5b506102a6600480360360208110156109a757600080fd5b5035612d5c565b6102a6600480360360208110156109c457600080fd5b5035612daa565b3480156109d757600080fd5b5061026a6130db565b3480156109ec57600080fd5b506102a660048036036040811015610a0357600080fd5b81359190810190604081016020820135600160201b811115610a2457600080fd5b820183602082011115610a3657600080fd5b803590602001918460018302840111600160201b83111715610a5757600080fd5b5090925090506130e1565b348015610a6e57600080fd5b5061026a613286565b348015610a8357600080fd5b50610a8c61328c565b6040805160ff9092168252519081900360200190f35b348015610aae57600080fd5b506102a660048036036020811015610ac557600080fd5b5035613291565b348015610ad857600080fd5b5061026a613418565b348015610aed57600080fd5b506102a660048036036020811015610b0457600080fd5b50356001600160a01b031661341e565b348015610b2057600080fd5b5061026a60048036036020811015610b3757600080fd5b5035613489565b60096020526000908152604090205481565b6000546001600160a01b03163314610b995760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600255565b6000546001600160a01b031681565b60018054604080516020600284861615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610c325780601f10610c0757610100808354040283529160200191610c32565b820191906000526020600020905b815481529060010190602001808311610c1557829003601f168201915b505050505081565b60008060088481548110610c4a57fe5b60009182526020909120600e9091020190506004600382015460ff166004811115610c7157fe5b14610c7c5750610e44565b60005b600c820154811015610e4157600082600c018281548110610c9c57fe5b60009182526020909120600360069092020190810154909150610100900460ff161580610cd45750600381015462010000900460ff16155b15610d09576001600160a01b038516600090815260058201602052604090206002810154600190910154019390930192610e38565b600d830154610dc357600080826001015411610d26576000610d62565b8160020154826001015460048401546001600160a01b038916600090815260058601602052604090209290910191600101540281610d6057fe5b045b9050600080836002015411610d78576000610db4565b8260020154836001015460048501546001600160a01b038a16600090815260058701602052604090209290910191600201540281610db257fe5b045b91909101949094019350610e38565b60008160000184600d015460038110610dd857fe5b015411610de6576000610e33565b600d830154819060038110610df757fe5b015460048201546001600160a01b03871660009081526005840160205260409020600d86015460038110610e2757fe5b01540281610e3157fe5b045b840193505b50600101610c7f565b50505b92915050565b600060088381548110610e5957fe5b60009182526020909120600e9091020190506001826002811115610e7957fe5b1480610e9057506002826002811115610e8e57fe5b145b610ecb5760405162461bcd60e51b81526004018080602001828103825260368152602001806139ec6036913960400191505060405180910390fd5b60038082015460ff166004811115610edf57fe5b14610f29576040805162461bcd60e51b81526020600482015260156024820152742737903234b9b83aba32903a379030b83832b0b61760591b604482015290519081900360640190fd5b60017f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03166310f169e883600b01546040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b158015610f9357600080fd5b505afa158015610fa7573d6000803e3d6000fd5b505050506040513d6020811015610fbd57600080fd5b50516002811115610fca57fe5b1461101c576040805162461bcd60e51b815260206004820152601a60248201527f44697370757465206973206e6f742061707065616c61626c652e000000000000604482015290519081900360640190fd5b6000807f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b031663afe15cfb84600b01546040518263ffffffff1660e01b815260040180828152602001915050604080518083038186803b15801561108657600080fd5b505afa15801561109a573d6000803e3d6000fd5b505050506040513d60408110156110b057600080fd5b50805160209091015190925090504282118015906110cd57508042105b6111085760405162461bcd60e51b815260040180806020018281038252602e815260200180613744602e913960400191505060405180910390fd5b60007f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b0316631c3db16d85600b01546040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561117257600080fd5b505afa158015611186573d6000803e3d6000fd5b505050506040513d602081101561119c57600080fd5b5051905060008560028111156111ae57fe5b8214156111be5750600654611216565b816111cc5750600554611216565b600284840304844203106112115760405162461bcd60e51b815260040180806020018281038252603e815260200180613803603e913960400191505060405180910390fd5b506007545b600c8501805460009190600019810190811061122e57fe5b906000526020600020906006020190508060030187600281111561124e57fe5b6003811061125857fe5b602081049091015460ff601f9092166101000a900416156112aa5760405162461bcd60e51b81526004018080602001828103825260218152602001806139a66021913960400191505060405180910390fd5b600b8601546040805163791f8b7360e11b8152600481018381526024820192835260018054600260001961010083851615020190911604604484018190526000956001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe28069169563f23f16e695919492909160640190849080156113745780601f1061134957610100808354040283529160200191611374565b820191906000526020600020905b81548152906001019060200180831161135757829003601f168201915b5050935050505060206040518083038186803b15801561139357600080fd5b505afa1580156113a7573d6000803e3d6000fd5b505050506040513d60208110156113bd57600080fd5b5051905060006113e36127106113d384876134b4565b816113da57fe5b849190046134e8565b90506000806114143461140f878e60028111156113fc57fe5b6003811061140657fe5b015486906134fd565b613518565b3360009081526005880160205260409020919350915082908c600281111561143857fe5b6003811061144257fe5b018054909101905581858c600281111561145857fe5b6003811061146257fe5b018054909101905560405133908d907f22039e79a27860a038aece214124c8ecef12fdc1334feb8e8a157a0ae16a1db4908e908690808360028111156114a457fe5b81526020018281526020019250505060405180910390a382858c60028111156114c957fe5b600381106114d357fe5b015410611583576001856003018c60028111156114ec57fe5b600381106114f657fe5b602091828204019190066101000a81548160ff021916908315150217905550846000018b600281111561152557fe5b6003811061152f57fe5b015460048601805490910190556040518c907f213276d821d6205d87fa4f4658db4bf5a24a2323b0fdd8ffcd239c445f86a57b908d908082600281111561157257fe5b815260200191505060405180910390a25b604051339082156108fc029083906000818181858888f1505050506003860154610100900460ff16905080156115c35750600385015462010000900460ff165b156116ed57600b8a01546040805163093225f160e31b8152600481018381526024820192835260018054600260001961010083851615020190911604604484018190526001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe2806916956349912f88958b95919492909160640190849080156116915780601f1061166657610100808354040283529160200191611691565b820191906000526020600020905b81548152906001019060200180831161167457829003601f168201915b505093505050506000604051808303818588803b1580156116b157600080fd5b505af11580156116c5573d6000803e3d6000fd5b505050600c8c0180546001018155600052505060048501546116e790856134fd565b60048601555b505050505050505050505050565b6000546001600160a01b031633146117445760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600555565b6000806008838154811061175957fe5b90600052602060002090600e0201905060025481600401544203118061179257506002600382015460ff16600481111561178f57fe5b14155b156117a6576001600160ff1b0391506118e2565b60405163f7434ea960e01b815260206004820190815260018054600260001961010083851615020190911604602484018190526000936001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe28069169363f7434ea9939290918291604490910190849080156118675780601f1061183c57610100808354040283529160200191611867565b820191906000526020600020905b81548152906001019060200180831161184a57829003601f168201915b50509250505060206040518083038186803b15801561188557600080fd5b505afa158015611899573d6000803e3d6000fd5b505050506040513d60208110156118af57600080fd5b505160068301546004549192506118de91612710916118ce91906134b4565b816118d557fe5b839190046134e8565b9250505b50919050565b60075481565b60045481565b6000806008838154811061190457fe5b90600052602060002090600e02019050806000015481600401544203118061193f57506000600382015460ff16600481111561193c57fe5b14155b1561194d57600091506118e2565b8060000154816004015442038260010154836002015403028161196c57fe5b04816001015401915050919050565b600081600281111561198957fe5b600084815260096020526040812054600880549394509092839081106119ab57fe5b600091825260208220600c600e9092020190810180549193509060001981019081106119d357fe5b906000526020600020906006020190507f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b0316336001600160a01b031614611a535760405162461bcd60e51b81526004018080602001828103825260218152602001806137e26021913960400191505060405180910390fd5b60038083015460ff166004811115611a6757fe5b14611aa35760405162461bcd60e51b81526004018080602001828103825260268152602001806137726026913960400191505060405180910390fd5b600381015460ff61010090910416151560011415611ac45760019350611ae1565b600381015462010000900460ff16151560011415611ae157600293505b85337f394027a5fa6e098a1191094d1719d6929b9abc535fcc0c8f448d6a4e75622276866002811115611b1057fe5b60408051918252519081900360200190a3611b3686856002811115611b3157fe5b61353d565b505050505050565b600060088481548110611b4d57fe5b90600052602060002090600e0201905060008390505b600c82015481108015611b7f5750821580611b7f575082840181105b15611b3657611b8f868683611e1a565b600101611b63565b60035481565b60055481565b611bab613725565b600060088581548110611bba57fe5b90600052602060002090600e02019050600081600c018581548110611bdb57fe5b600091825260208083206001600160a01b03881684526005600690930201918201905260409182902082516060810190935290925060038282826020028201915b815481526020019060010190808311611c1c575050505050925050509392505050565b7f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe2806981565b60008060088381548110611c7357fe5b90600052602060002090600e020190508060000154816004015442031180611cae57506000600382015460ff166004811115611cab57fe5b14155b15611cc2576001600160ff1b0391506118e2565b600081600001548260040154420383600101548460020154030281611ce357fe5b60018481015460405163f7434ea960e01b81526020600482019081528354600281861615610100026000190190911604602483018190529590940490910194506000937f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03169363f7434ea99392909182916044019084908015611daf5780601f10611d8457610100808354040283529160200191611daf565b820191906000526020600020905b815481529060010190602001808311611d9257829003601f168201915b50509250505060206040518083038186803b158015611dcd57600080fd5b505afa158015611de1573d6000803e3d6000fd5b505050506040513d6020811015611df757600080fd5b5051600354909150611e1190612710906118ce90856134b4565b95945050505050565b600060088381548110611e2957fe5b90600052602060002090600e02019050600081600c018381548110611e4a57fe5b6000918252602090912060069091020190506004600383015460ff166004811115611e7157fe5b14611ec3576040805162461bcd60e51b815260206004820152601c60248201527f546865207461736b2073686f756c64206265207265736f6c7665642e00000000604482015290519081900360640190fd5b6003810154600090610100900460ff161580611eea5750600382015462010000900460ff16155b15611f2457506001600160a01b038516600090815260058201602052604081206002810180546001909201805490849055929055016120a2565b600d83015461200157600080836001015411611f41576000611f7d565b8260020154836001015460048501546001600160a01b038a16600090815260058701602052604090209290910191600101540281611f7b57fe5b045b9050600080846002015411611f93576000611fcf565b8360020154846001015460048601546001600160a01b038b16600090815260058801602052604090209290910191600201540281611fcd57fe5b045b6001600160a01b0389166000908152600586016020526040812060018101829055600201559190910191506120a29050565b60008260000184600d01546003811061201657fe5b015411612024576000612071565b600d83015482906003811061203557fe5b015460048301546001600160a01b03881660009081526005850160205260409020600d8601546003811061206557fe5b0154028161206f57fe5b045b6001600160a01b03871660009081526005840160205260408120600d86015492935090916003811061209f57fe5b01555b6040516001600160a01b0387169082156108fc029083906000818181858888f15050505050505050505050565b60065481565b6000833410156121165760405162461bcd60e51b8152600401808060200182810382526041815260200180613a486041913960600191505060405180910390fd5b4285116121545760405162461bcd60e51b81526004018080602001828103825260258152602001806139c76025913960400191505060405180910390fd5b506008805460018101825560009190915242808603600e83027ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee381019182557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee48101879055347ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee582018190557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee78201939093557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee8810180546001600160a01b031916331790557ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee90191909155604080516020808252810185905283917f61606860eb6c87306811e2695215385101daab53bd6ab4e9f9049aead9363c7d91879187919081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2604080514281529051339184917f6cf53aa7292e664152c2ea948c3b3c95d4b05c36daeb2626d0293473c4a4a1539181900360200190a350949350505050565b60006008848154811061231157fe5b6000918252602080832060405163f7434ea960e01b8152600481019283526001805460026000196101008385161502019091160460248301819052600e90950290920195506001600160a01b037f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe28069169363f7434ea993918291604490910190849080156123df5780601f106123b4576101008083540402835291602001916123df565b820191906000526020600020905b8154815290600101906020018083116123c257829003601f168201915b50509250505060206040518083038186803b1580156123fd57600080fd5b505afa158015612411573d6000803e3d6000fd5b505050506040513d602081101561242757600080fd5b5051600683015460045491925060009161244891612710916113d3916134b4565b90506002600384015460ff16600481111561245f57fe5b146124b1576040805162461bcd60e51b815260206004820181905260248201527f546865207461736b20697320696e207468652077726f6e67207374617475732e604482015290519081900360640190fd5b6002548360040154420311156124f85760405162461bcd60e51b81526004018080602001828103825260248152602001806139826024913960400191505060405180910390fd5b803410156125375760405162461bcd60e51b815260040180806020018281038252602a815260200180613864602a913960400191505060405180910390fd5b6003838101805460ff19169091179055600a830180546001600160a01b031916331790556040805163c13517e160e01b8152600260048201818152602483019384526001805460001981831615610100020116839004604485018190527f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03169563c13517e195899594926064909101908490801561261e5780601f106125f35761010080835404028352916020019161261e565b820191906000526020600020905b81548152906001019060200180831161260157829003601f168201915b505093505050506020604051808303818588803b15801561263e57600080fd5b505af1158015612652573d6000803e3d6000fd5b50505050506040513d602081101561266957600080fd5b5051600b84018190556000908152600960205260408120879055600c840180546001018155905260078301546126ab9083906126a590846134e8565b906134fd565b60078401556040513482900390339082156108fc029083906000818181858888f193505050505083600b01547f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03167f74baab670a4015ab2f1b467c5252a96141a2573f2908e58a92081e80d3cfde3d898a604051808381526020018281526020019250505060405180910390a3604080514281529051339189917f6f0bb1c54bb0ad8822894f45a3837ab62e23e77d25c5881ab57e1c6a99f7e0b59181900360200190a3841561281357336001600160a01b0316877f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03167fdccf2f8b2cc26eafcd61905cba744cff4b81d14740725f6376390dc6298a6a3c898960405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a45b50505050505050565b612824613725565b61282c613725565b6000806008868154811061283c57fe5b90600052602060002090600e02019050600081600c01868154811061285d57fe5b9060005260206000209060060201905080600001816003018260040154826003806020026040519081016040528092919082600380156128b2576020028201915b81548152602001906001019080831161289e575b5050604080516060810191829052949750869350600392509050826000855b825461010083900a900460ff1615158152602060019283018181049485019490930390920291018084116128d15790505050505050915094509450945050509250925092565b6008818154811061292757600080fd5b60009182526020909120600e9091020180546001820154600283015460038401546004850154600586015460068701546007880154600b890154600d909901549799509597949660ff9094169592946001600160a01b0390921693909291908a565b6000546001600160a01b031633146129d25760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600755565b6129df613725565b6000600883815481106129ee57fe5b60009182526020909120604080516060810191829052600e9093029091019250600883019060039082845b81546001600160a01b03168152600190910190602001808311612a19575050505050915050919050565b600060088481548110612a5257fe5b60009182526020909120600e9091020190506004600382015460ff166004811115612a7957fe5b1415612ab65760405162461bcd60e51b8152600401808060200182810382526026815260200180613a226026913960400191505060405180910390fd5b336001600160a01b0316847f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03167fdccf2f8b2cc26eafcd61905cba744cff4b81d14740725f6376390dc6298a6a3c868660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a450505050565b6000546001600160a01b03163314612b9a5760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600355565b600060088281548110612bae57fe5b60009182526020909120600e9091020190506002600382015460ff166004811115612bd557fe5b10612c115760405162461bcd60e51b815260040180806020018281038252602d815260200180613955602d913960400191505060405180910390fd5b80546004820154420311612c565760405162461bcd60e51b81526004018080602001828103825260328152602001806138f66032913960400191505060405180910390fd5b60038101805460ff1916600417905560078101546006820154600583015460405191909201916001600160a01b0316906108fc8315029083906000818181858888f150506000600686018190556007860155505060408051426020820152818152601481830152731c995c5d595cdd195c8b5c995a5b589d5c9cd95960621b606082015290518592507f5850eca3b971056e7a311e04b06c359c0aceec8e422e4e015301e136efbd888a9181900360800190a2505050565b6000546001600160a01b03163314612d575760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600655565b6000546001600160a01b03163314612da55760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600455565b600060088281548110612db957fe5b90600052602060002090600e020190508060000154816004015442031115612e28576040805162461bcd60e51b815260206004820181905260248201527f54686520646561646c696e652068617320616c7265616479207061737365642e604482015290519081900360640190fd5b600081600001548260040154420383600101548460020154030281612e4957fe5b60018481015460405163f7434ea960e01b81526020600482019081528354600281861615610100026000190190911604602483018190529590940490910194506000937f000000000000000000000000988b3a538b618c7a603e1c11ab82cd16dbe280696001600160a01b03169363f7434ea99392909182916044019084908015612f155780601f10612eea57610100808354040283529160200191612f15565b820191906000526020600020905b815481529060010190602001808311612ef857829003601f168201915b50509250505060206040518083038186803b158015612f3357600080fd5b505afa158015612f47573d6000803e3d6000fd5b505050506040513d6020811015612f5d57600080fd5b5051600354909150600090612f7a90612710906113d390866134b4565b90506000600385015460ff166004811115612f9157fe5b14612fcd5760405162461bcd60e51b815260040180806020018281038252602d815260200180613928602d913960400191505060405180910390fd5b8034101561300c5760405162461bcd60e51b8152600401808060200182810382526033815260200180613a896033913960400191505060405180910390fd5b6009840180546001600160a01b0319163317905560038401805460ff191660011790556002840154600585015460405191859003916001600160a01b0391909116906108fc8315029083906000818181858888f150505050600686018590555050600784018190556040513482900390339082156108fc029083906000818181858888f150506040805188815242602082015281513395508b94507f9c8de00bfaaca6ca425ca3047c87c81f398e79f7c15166f53dcb29782ef9da4293509081900390910190a3505050505050565b60085490565b6000600884815481106130f057fe5b60009182526020909120600e9091020190506001600382015460ff16600481111561311757fe5b146131535760405162461bcd60e51b815260040180806020018281038252604a815260200180613798604a913960600191505060405180910390fd5b80546004820154420311156131af576040805162461bcd60e51b815260206004820181905260248201527f54686520646561646c696e652068617320616c7265616479207061737365642e604482015290519081900360640190fd5b60088101600101546001600160a01b031633146131fd5760405162461bcd60e51b815260040180806020018281038252603f8152602001806138b7603f913960400191505060405180910390fd5b60038101805460ff1916600217905542600482018190556040805160208101839052818152908101849052339186917f81c1cc8daea412565717a44fb42a08dbcb5d73101f5473d062391293c947d26d9187918791908060608101858580828437600083820152604051601f909101601f1916909201829003965090945050505050a350505050565b60025481565b600081565b6000600882815481106132a057fe5b60009182526020909120600e9091020190506002600382015460ff1660048111156132c757fe5b14613319576040805162461bcd60e51b815260206004820181905260248201527f546865207461736b20697320696e207468652077726f6e67207374617475732e604482015290519081900360640190fd5b600254816004015442031161335f5760405162461bcd60e51b81526004018080602001828103825260238152602001806138416023913960400191505060405180910390fd5b60038101805460ff19166004179055600781015460068201540160088201600101546040516001600160a01b039091169082156108fc029083906000818181858888f150506000600686018190556007860155505060408051426020820152818152601481830152731d1c985b9cdb185d1a5bdb8b5858d8d95c1d195960621b606082015290518592507f5850eca3b971056e7a311e04b06c359c0aceec8e422e4e015301e136efbd888a9181900360800190a2505050565b61271081565b6000546001600160a01b031633146134675760405162461bcd60e51b815260040180806020018281038252602981526020018061388e6029913960400191505060405180910390fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000806008838154811061349957fe5b60009182526020909120600e90910201600c01549392505050565b6000826134c357506000610e44565b828202828482816134d057fe5b04146134de576000196134e0565b805b949350505050565b6000828201838110156134de576000196134e0565b60008282111561350f57506000610e44565b50808203610e44565b6000808383111561352e57508290506000613536565b508190508083035b9250929050565b600082815260096020526040812054600880549192918390811061355d57fe5b6000918252602082206003600e90920201908101805460ff19166004179055600d810185905591508361363857600582015460068301546040516001600160a01b039092169181156108fc0291906000818181858888f193505050505060028260070154816135c857fe5b60098401546040519290910492506001600160a01b0316906108fc8315029083906000818181858888f1505050600884019150600290505b6003811061360a57fe5b01546040516001600160a01b039091169082156108fc029083906000818181858888f19350505050506136b6565b600184141561365857506007810154600682015401600882016001613600565b600582015460068301546040516001600160a01b039092169181156108fc0291906000818181858888f150505050600a83015460078401546040516001600160a01b03909216925080156108fc02916000818181858888f150505050505b600060068301819055600783015560408051426020820152818152600f818301526e191a5cdc1d5d194b5cd95d1d1b1959608a1b6060820152905184917f5850eca3b971056e7a311e04b06c359c0aceec8e422e4e015301e136efbd888a919081900360800190a25050505050565b6040518060600160405280600390602082028036833750919291505056fe46756e64696e67206d757374206265206d6164652077697468696e207468652061707065616c20706572696f642e54686520646973707574652068617320616c7265616479206265656e207265736f6c7665642e546865207461736b20697320656974686572206e6f742061737369676e6564206f72207472616e736c6174696f6e2068617320616c7265616479206265656e207375626d69747465642e4d7573742062652063616c6c6564206279207468652061726269747261746f722e546865206c6f736572206d7573742070617920647572696e67207468652066697273742068616c66206f66207468652061707065616c20706572696f642e54686520726576696577207068617365206861736e277420706173736564207965742e4e6f7420656e6f7567682045544820746f20636f766572206368616c6c656e6765206465706f7369742e4f6e6c7920676f7665726e6f7220697320616c6c6f77656420746f20706572666f726d20746869732e43616e2774207375626d6974207472616e736c6174696f6e20746f2061207461736b2074686174207761736e27742061737369676e656420746f20796f752e43616e2774207265696d62757273652069662074686520646561646c696e65206861736e277420706173736564207965742e5461736b2068617320616c7265616479206265656e2061737369676e6564206f72207265696d6275727365642e43616e2774207265696d6275727365206966207472616e736c6174696f6e20776173207375626d69747465642e546865207265766965772070686173652068617320616c7265616479207061737365642e41707065616c206665652068617320616c7265616479206265656e20706169642e54686520646561646c696e652073686f756c6420626520696e20746865206675747572652e526563697069656e74206d7573742062652065697468657220746865207472616e736c61746f72206f72206368616c6c656e6765722e546865207461736b206d757374206e6f7420616c7265616479206265207265736f6c7665642e4465706f73697465642076616c75652073686f756c642062652067726561746572207468616e206f7220657175616c20746f20746865206d696e2070726963652e4e6f7420656e6f7567682045544820746f20726561636820746865207265717569726564206465706f7369742076616c75652ea26469706673582212203515ad57a5cb9f5e12f5aee09364ffc2498a2b8ccab69895db70f2fb17d0fbea64736f6c63430007040033
[ 13, 25, 11 ]
0x46a8Dfa8A9c478FF0840099b3A39Ea98a6644eED
pragma solidity 0.7.1; 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); } } } } abstract contract Context { function _msgSender() internal virtual view returns (address payable) { return msg.sender; } function _msgData() internal virtual view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract ERC20Storage { // The state variables we care about. bytes32 constant DIAMOND_STORAGE_POSITION_ERC20 = keccak256( "diamond.standard.diamond.storage.erc20" ); struct TokenStorage { string name; string symbol; uint8 decimals; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowances; uint256 totalSupply; } // Creates and returns the storage pointer to the struct. function erc20Storage() internal pure returns (TokenStorage storage ms) { bytes32 position = DIAMOND_STORAGE_POSITION_ERC20; assembly { ms.slot := position } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } contract 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 Migrations { address public owner; uint256 public last_completed_migration; constructor() { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint256 completed) public restricted { last_completed_migration = completed; } } abstract contract Ownable is Initializable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function _onInitialize(address sender) internal 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 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; } } contract PauserRole is Initializable { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public virtual initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require( isPauser(msg.sender), "PauserRole: caller does not have the Pauser role" ); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(msg.sender); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } uint256[50] private ______gap; } abstract contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback() external payable { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual 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 { 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 virtual {} /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } library Roles { struct Role { mapping(address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } abstract contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); bytes32 constant DIAMOND_STORAGE_POSITION = keccak256( "diamond.standard.diamond.storage.proxy" ); struct DiamondStorage { // owner of the contract address proxyAdmin; address implementation; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } /** * @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 impl Address of the current implementation */ function _implementation() internal override view returns (address) { DiamondStorage storage ms = diamondStorage(); return ms.implementation; } /** * @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" ); DiamondStorage storage ms = diamondStorage(); require( newImplementation != ms.implementation, "Proxy implementation is already set to this address" ); ms.implementation = newImplementation; } } contract CanReclaimEther is Ownable { function reclaimEther() external onlyOwner { msg.sender.transfer(address(this).balance); } } contract CanReclaimToken is Ownable { using SafeERC20 for IERC20; function reclaimToken(IERC20 token) external onlyOwner { uint256 balance = token.balanceOf(address(this)); token.safeTransfer(owner(), balance); } } contract ERC20 is Context, Initializable, IERC20, ERC20Storage { using SafeMath for uint256; using Address for address; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ function initialize( string memory name, string memory symbol, uint8 decimals ) public initializer { _onInitialize(name, symbol, decimals); } function _onInitialize( string memory name, string memory symbol, uint8 decimals ) internal initializer { TokenStorage storage ercs = erc20Storage(); ercs.name = name; ercs.symbol = symbol; ercs.decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { TokenStorage storage ercs = erc20Storage(); return ercs.name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { TokenStorage storage ercs = erc20Storage(); return ercs.symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { TokenStorage storage ercs = erc20Storage(); return ercs.decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { TokenStorage storage ercs = erc20Storage(); return ercs.totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { TokenStorage storage ercs = erc20Storage(); return ercs.balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public virtual override view returns (uint256) { TokenStorage storage ercs = erc20Storage(); return ercs.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); TokenStorage storage ercs = erc20Storage(); _approve( sender, _msgSender(), ercs.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) { TokenStorage storage ercs = erc20Storage(); _approve( _msgSender(), spender, ercs.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) { TokenStorage storage ercs = erc20Storage(); _approve( _msgSender(), spender, ercs.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"); TokenStorage storage ercs = erc20Storage(); _beforeTokenTransfer(sender, recipient, amount); ercs.balances[sender] = ercs.balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); ercs.balances[recipient] = ercs.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); TokenStorage storage ercs = erc20Storage(); ercs.totalSupply = ercs.totalSupply.add(amount); ercs.balances[account] = ercs.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); TokenStorage storage ercs = erc20Storage(); ercs.balances[account] = ercs.balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); ercs.totalSupply = ercs.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"); TokenStorage storage ercs = erc20Storage(); ercs.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 { TokenStorage storage ercs = erc20Storage(); ercs.decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[50] private ______gap; } 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); } } abstract 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 virtual payable { require(_implementation() == address(0)); assert( DIAMOND_STORAGE_POSITION == keccak256("diamond.standard.diamond.storage.proxy") ); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } contract Pausable is Initializable, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public override initializer { PauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(msg.sender); } uint256[50] private ______gap; } abstract 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) payable { assert( DIAMOND_STORAGE_POSITION == keccak256("diamond.standard.diamond.storage.proxy") ); //assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } } } abstract 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, "upgradeToAndCall: delegatecall should be successfull" ); } /** * @return adm The admin slot. */ function _admin() internal view returns (address) { DiamondStorage storage ms = diamondStorage(); return ms.proxyAdmin; } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { DiamondStorage storage ms = diamondStorage(); ms.proxyAdmin = newAdmin; } /** * @dev Only fall back when the sender is not the admin. */ /* function _willFallback() override(Proxy) internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } */ } 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"); } } contract OwnedUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, InitializableUpgradeabilityProxy { /** * 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. */ function initialize( address _logic, address _admin, bytes memory _data ) public payable { require(_implementation() == address(0)); InitializableUpgradeabilityProxy.initialize(_logic, _data); _setAdmin(_admin); emit Initialized(_admin, _logic); } event Initialized(address admin, address _logic); /** * @dev Only fall back when the sender is not the admin. */ // prettier-ignore function _willFallback() override internal { require( _admin() != address(0), "Can't fallback if admin is not set" ); require( msg.sender != _admin(), "Cannot call fallback function from the proxy admin" ); super._willFallback(); } } contract UbxToken is Initializable, Ownable, ERC20, ERC20Burnable, ERC20Pausable, CanReclaimEther, CanReclaimToken { function initialize( string memory name, string memory symbol, uint8 decimals, uint256 initialSupply, address initialHolder, address owner, address[] memory pausers ) public initializer { require(pausers.length > 0, "At least one pauser should be defined"); ERC20.initialize(name, symbol, decimals); Ownable._onInitialize(owner); Pausable.initialize(pausers[0]); for (uint256 i = 1; i < pausers.length; ++i) { _addPauser(pausers[i]); } // create the tokens _mint(initialHolder, initialSupply); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } }
0x608060405234801561001057600080fd5b50600436106101c45760003560e01c8063715018a6116100f95780639847a62411610097578063a9059cbb11610071578063a9059cbb14610792578063c4d66de8146107be578063dd62ed3e146107e4578063f2fde38b14610812576101c4565b80639847a6241461058d5780639f727c271461075e578063a457c2d714610766576101c4565b80638456cb59116100d35780638456cb59146105515780638da5cb5b146105595780638f32d59b1461057d57806395d89b4114610585576101c4565b8063715018a6146104f757806379cc6790146104ff57806382dc1ec41461052b576101c4565b8063395093511161016657806346fbf68e1161014057806346fbf68e1461049b5780635c975abb146104c15780636ef8d66d146104c957806370a08231146104d1576101c4565b8063395093511461044a5780633f4ba83a1461047657806342966c681461047e576101c4565b806317ffc320116101a257806317ffc320146103b657806318160ddd146103dc57806323b872dd146103f6578063313ce5671461042c576101c4565b806306fdde03146101c9578063095ea7b3146102465780631624f6c614610286575b600080fd5b6101d1610838565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561020b5781810151838201526020016101f3565b50505050905090810190601f1680156102385780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102726004803603604081101561025c57600080fd5b506001600160a01b0381351690602001356108d6565b604080519115158252519081900360200190f35b6103b46004803603606081101561029c57600080fd5b810190602081018135600160201b8111156102b657600080fd5b8201836020820111156102c857600080fd5b803590602001918460018302840111600160201b831117156102e957600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b81111561033b57600080fd5b82018360208201111561034d57600080fd5b803590602001918460018302840111600160201b8311171561036e57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505050903560ff1691506108f39050565b005b6103b4600480360360208110156103cc57600080fd5b50356001600160a01b03166109a3565b6103e4610a87565b60408051918252519081900360200190f35b6102726004803603606081101561040c57600080fd5b506001600160a01b03813581169160208101359091169060400135610a9c565b610434610b32565b6040805160ff9092168252519081900360200190f35b6102726004803603604081101561046057600080fd5b506001600160a01b038135169060200135610b4a565b6103b4610baf565b6103b46004803603602081101561049457600080fd5b5035610c80565b610272600480360360208110156104b157600080fd5b50356001600160a01b0316610c94565b610272610ca7565b6103b4610cb0565b6103e4600480360360208110156104e757600080fd5b50356001600160a01b0316610cbb565b6103b4610cea565b6103b46004803603604081101561051557600080fd5b506001600160a01b038135169060200135610d7b565b6103b46004803603602081101561054157600080fd5b50356001600160a01b0316610dd5565b6103b4610e22565b610561610ef3565b604080516001600160a01b039092168252519081900360200190f35b610272610f02565b6101d1610f13565b6103b4600480360360e08110156105a357600080fd5b810190602081018135600160201b8111156105bd57600080fd5b8201836020820111156105cf57600080fd5b803590602001918460018302840111600160201b831117156105f057600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b81111561064257600080fd5b82018360208201111561065457600080fd5b803590602001918460018302840111600160201b8311171561067557600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929560ff853516956020860135956001600160a01b0360408201358116965060608201351694509192509060a081019060800135600160201b8111156106ed57600080fd5b8201836020820111156106ff57600080fd5b803590602001918460208302840111600160201b8311171561072057600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550610f8e945050505050565b6103b46110e3565b6102726004803603604081101561077c57600080fd5b506001600160a01b038135169060200135611156565b610272600480360360408110156107a857600080fd5b506001600160a01b0381351690602001356111cb565b6103b4600480360360208110156107d457600080fd5b50356001600160a01b03166111df565b6103e4600480360360408110156107fa57600080fd5b506001600160a01b0381358116916020013516611294565b6103b46004803603602081101561082857600080fd5b50356001600160a01b03166112d0565b60606000610844611320565b805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292935083918301828280156108cb5780601f106108a0576101008083540402835291602001916108cb565b820191906000526020600020905b8154815290600101906020018083116108ae57829003601f168201915b505050505091505090565b60006108ea6108e3611344565b8484611348565b50600192915050565b600054610100900460ff168061090c575061090c611447565b8061091a575060005460ff16155b6109555760405162461bcd60e51b815260040180806020018281038252602e8152602001806122a8602e913960400191505060405180910390fd5b600054610100900460ff16158015610980576000805460ff1961ff0019909116610100171660011790555b61098b84848461144d565b801561099d576000805461ff00191690555b50505050565b6109ab610f02565b6109ea576040805162461bcd60e51b81526020600482018190526024820152600080516020612266833981519152604482015290519081900360640190fd5b6000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015610a3957600080fd5b505afa158015610a4d573d6000803e3d6000fd5b505050506040513d6020811015610a6357600080fd5b50519050610a83610a72610ef3565b6001600160a01b0384169083611537565b5050565b600080610a92611320565b6005015491505090565b6000610aa9848484611589565b6000610ab3611320565b9050610b2785610ac1611344565b610b228660405180606001604052806028815260200161223e602891396001600160a01b038b166000908152600488016020526040812090610b01611344565b6001600160a01b0316815260208101919091526040016000205491906116f9565b611348565b506001949350505050565b600080610b3d611320565b6002015460ff1691505090565b600080610b55611320565b9050610ba5610b62611344565b85610b2286856004016000610b75611344565b6001600160a01b03908116825260208083019390935260409182016000908120918d168152925290205490611790565b5060019392505050565b610bb833610c94565b610bf35760405162461bcd60e51b815260040180806020018281038252603081526020018061215a6030913960400191505060405180910390fd5b60995460ff16610c41576040805162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015290519081900360640190fd5b6099805460ff191690556040805133815290517f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa9181900360200190a1565b610c91610c8b611344565b826117f1565b50565b6000610ca1606683611902565b92915050565b60995460ff1690565b610cb933611969565b565b600080610cc6611320565b6001600160a01b038416600090815260039091016020526040902054915050919050565b610cf2610f02565b610d31576040805162461bcd60e51b81526020600482018190526024820152600080516020612266833981519152604482015290519081900360640190fd5b6033546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3603380546001600160a01b0319169055565b6000610db2826040518060600160405280602481526020016122d660249139610dab86610da6611344565b611294565b91906116f9565b9050610dc683610dc0611344565b83611348565b610dd083836117f1565b505050565b610dde33610c94565b610e195760405162461bcd60e51b815260040180806020018281038252603081526020018061215a6030913960400191505060405180910390fd5b610c91816119ab565b610e2b33610c94565b610e665760405162461bcd60e51b815260040180806020018281038252603081526020018061215a6030913960400191505060405180910390fd5b60995460ff1615610eb1576040805162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015290519081900360640190fd5b6099805460ff191660011790556040805133815290517f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2589181900360200190a1565b6033546001600160a01b031690565b6033546001600160a01b0316331490565b60606000610f1f611320565b9050806001018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108cb5780601f106108a0576101008083540402835291602001916108cb565b600054610100900460ff1680610fa75750610fa7611447565b80610fb5575060005460ff16155b610ff05760405162461bcd60e51b815260040180806020018281038252602e8152602001806122a8602e913960400191505060405180910390fd5b600054610100900460ff1615801561101b576000805460ff1961ff0019909116610100171660011790555b600082511161105b5760405162461bcd60e51b81526004018080602001828103825260258152602001806121d26025913960400191505060405180910390fd5b6110668888886108f3565b61106f836119ed565b61108c8260008151811061107f57fe5b60200260200101516111df565b60015b82518110156110bc576110b48382815181106110a757fe5b60200260200101516119ab565b60010161108f565b506110c78486611ade565b80156110d9576000805461ff00191690555b5050505050505050565b6110eb610f02565b61112a576040805162461bcd60e51b81526020600482018190526024820152600080516020612266833981519152604482015290519081900360640190fd5b60405133904780156108fc02916000818181858888f19350505050158015610c91573d6000803e3d6000fd5b600080611161611320565b9050610ba561116e611344565b85610b228660405180606001604052806025815260200161238e6025913986600401600061119a611344565b6001600160a01b03908116825260208083019390935260409182016000908120918e168152925290205491906116f9565b60006108ea6111d8611344565b8484611589565b600054610100900460ff16806111f857506111f8611447565b80611206575060005460ff16155b6112415760405162461bcd60e51b815260040180806020018281038252602e8152602001806122a8602e913960400191505060405180910390fd5b600054610100900460ff1615801561126c576000805460ff1961ff0019909116610100171660011790555b61127582611be6565b6099805460ff191690558015610a83576000805461ff00191690555050565b60008061129f611320565b6001600160a01b03948516600090815260049190910160209081526040808320959096168252939093525050205490565b6112d8610f02565b611317576040805162461bcd60e51b81526020600482018190526024820152600080516020612266833981519152604482015290519081900360640190fd5b610c9181611c9e565b7fbbdabd1f87dfba3cc4b2e8c64895a5475ba33474ee39ad3552fb911b75018e7090565b3390565b6001600160a01b03831661138d5760405162461bcd60e51b81526004018080602001828103825260248152602001806123406024913960400191505060405180910390fd5b6001600160a01b0382166113d25760405162461bcd60e51b81526004018080602001828103825260228152602001806121b06022913960400191505060405180910390fd5b60006113dc611320565b6001600160a01b03808616600081815260048401602090815260408083209489168084529482529182902087905581518781529151949550929391927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92592918290030190a350505050565b303b1590565b600054610100900460ff16806114665750611466611447565b80611474575060005460ff16155b6114af5760405162461bcd60e51b815260040180806020018281038252602e8152602001806122a8602e913960400191505060405180910390fd5b600054610100900460ff161580156114da576000805460ff1961ff0019909116610100171660011790555b60006114e4611320565b85519091506114f99082906020880190612081565b50835161150f9060018301906020870190612081565b50600201805460ff191660ff8416179055801561099d576000805461ff001916905550505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610dd0908490611d3f565b6001600160a01b0383166115ce5760405162461bcd60e51b815260040180806020018281038252602581526020018061231b6025913960400191505060405180910390fd5b6001600160a01b0382166116135760405162461bcd60e51b81526004018080602001828103825260238152602001806121156023913960400191505060405180910390fd5b600061161d611320565b905061162a848484611ef7565b611669826040518060600160405280602681526020016121f7602691396001600160a01b038716600090815260038501602052604090205491906116f9565b6001600160a01b038086166000908152600384016020526040808220939093559085168152205461169a9083611790565b6001600160a01b03808516600081815260038501602090815260409182902094909455805186815290519193928816927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a350505050565b600081848411156117885760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561174d578181015183820152602001611735565b50505050905090810190601f16801561177a5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6000828201838110156117ea576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6001600160a01b0382166118365760405162461bcd60e51b81526004018080602001828103825260218152602001806122fa6021913960400191505060405180910390fd5b61184282600083611ef7565b600061184c611320565b905061188d82604051806060016040528060228152602001612138602291396001600160a01b038616600090815260038501602052604090205491906116f9565b6001600160a01b038416600090815260038301602052604090205560058101546118b79083611f02565b60058201556040805183815290516000916001600160a01b038616917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a3505050565b60006001600160a01b0382166119495760405162461bcd60e51b81526004018080602001828103825260228152602001806122866022913960400191505060405180910390fd5b506001600160a01b03166000908152602091909152604090205460ff1690565b611974606682611f44565b6040516001600160a01b038216907fcd265ebaf09df2871cc7bd4133404a235ba12eff2041bb89d9c714a2621c7c7e90600090a250565b6119b6606682611fab565b6040516001600160a01b038216907f6719d08c1888103bea251a4ed56406bd0c3e69723c8a1686e017e7bbe159b6f890600090a250565b600054610100900460ff1680611a065750611a06611447565b80611a14575060005460ff16155b611a4f5760405162461bcd60e51b815260040180806020018281038252602e8152602001806122a8602e913960400191505060405180910390fd5b600054610100900460ff16158015611a7a576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a38015610a83576000805461ff00191690555050565b6001600160a01b038216611b39576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b611b4560008383611ef7565b6000611b4f611320565b6005810154909150611b619083611790565b60058201556001600160a01b0383166000908152600382016020526040902054611b8b9083611790565b6001600160a01b038416600081815260038401602090815260408083209490945583518681529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a3505050565b600054610100900460ff1680611bff5750611bff611447565b80611c0d575060005460ff16155b611c485760405162461bcd60e51b815260040180806020018281038252602e8152602001806122a8602e913960400191505060405180910390fd5b600054610100900460ff16158015611c73576000805460ff1961ff0019909116610100171660011790555b611c7c82610c94565b611c8957611c89826119ab565b8015610a83576000805461ff00191690555050565b6001600160a01b038116611ce35760405162461bcd60e51b815260040180806020018281038252602681526020018061218a6026913960400191505060405180910390fd5b6033546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b611d51826001600160a01b031661202c565b611da2576040805162461bcd60e51b815260206004820152601f60248201527f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e747261637400604482015290519081900360640190fd5b60006060836001600160a01b0316836040518082805190602001908083835b60208310611de05780518252601f199092019160209182019101611dc1565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611e42576040519150601f19603f3d011682016040523d82523d6000602084013e611e47565b606091505b509150915081611e9e576040805162461bcd60e51b815260206004820181905260248201527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564604482015290519081900360640190fd5b80511561099d57808060200190516020811015611eba57600080fd5b505161099d5760405162461bcd60e51b815260040180806020018281038252602a815260200180612364602a913960400191505060405180910390fd5b610dd0838383612032565b60006117ea83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506116f9565b611f4e8282611902565b611f895760405162461bcd60e51b815260040180806020018281038252602181526020018061221d6021913960400191505060405180910390fd5b6001600160a01b0316600090815260209190915260409020805460ff19169055565b611fb58282611902565b15612007576040805162461bcd60e51b815260206004820152601f60248201527f526f6c65733a206163636f756e7420616c72656164792068617320726f6c6500604482015290519081900360640190fd5b6001600160a01b0316600090815260209190915260409020805460ff19166001179055565b3b151590565b61203d838383610dd0565b612045610ca7565b15610dd05760405162461bcd60e51b815260040180806020018281038252602a8152602001806123b3602a913960400191505060405180910390fd5b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106120c257805160ff19168380011785556120ef565b828001600101855582156120ef579182015b828111156120ef5782518255916020019190600101906120d4565b506120fb9291506120ff565b5090565b5b808211156120fb576000815560010161210056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e6365506175736572526f6c653a2063616c6c657220646f6573206e6f742068617665207468652050617573657220726f6c654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f20616464726573734174206c65617374206f6e65207061757365722073686f756c6420626520646566696e656445524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e6365526f6c65733a206163636f756e7420646f6573206e6f74206861766520726f6c6545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e63654f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572526f6c65733a206163636f756e7420697320746865207a65726f2061646472657373436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a656445524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573735361666545524332303a204552433230206f7065726174696f6e20646964206e6f74207375636365656445524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f45524332305061757361626c653a20746f6b656e207472616e73666572207768696c6520706175736564a2646970667358221220fe5c7d5b8857266e94b2b5be6883d640b224362cc4506c05fe71763f480c291e64736f6c63430007010033
[ 15, 20 ]
0x4747ca5474f3044e3f9d3b8dc237e9c9f3a8fc04
pragma solidity 0.5.17; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } 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 IRewardDistributionRecipient is Ownable { address public rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } 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 SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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); } } contract LPTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public uni = IERC20(0x399c74F05C912D60329b038d52628558f28E4f7e); //univ2 lp token 0x399c74F05C912D60329b038d52628558f28E4f7e uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); uni.safeTransferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); uni.safeTransfer(msg.sender, amount); } } contract Unipool is LPTokenWrapper, IRewardDistributionRecipient { IERC20 public ari = IERC20(0x8A8b5318d3A59fa6D1d0A83A1B0506f2796b5670); //Z ropsten 0x188112F59323230a81776E89E38BD3ee85E7E01E - Denarii ARI mainnet 0x8A8b5318d3A59fa6D1d0A83A1B0506f2796b5670 uint256 public constant DURATION = 7 days; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e8) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e8) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) { uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; ari.safeTransfer(msg.sender, reward); //Use transfer instead of safeTransfer emit RewardPaid(msg.sender, reward); } } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } }
0x608060405234801561001057600080fd5b50600436106101725760003560e01c806380faa57d116100de578063c8f33c9111610097578063e9fad8ee11610071578063e9fad8ee1461058b578063ebe2b12b14610595578063edc9af95146105b3578063f2fde38b146105fd57610172565b8063c8f33c9114610531578063cd3daf9d1461054f578063df136d651461056d57610172565b806380faa57d146103d75780638b876347146103f55780638da5cb5b1461044d5780638f32d59b1461049757806397da8997146104b9578063a694fc3a1461050357610172565b80632e1a7d4d116101305780632e1a7d4d146102f15780633c6b16ab1461031f5780633d18b9121461034d57806370a0823114610357578063715018a6146103af5780637b0a47ee146103b957610172565b80628cc262146101775780630700037d146101cf5780630d68b76114610227578063101114cf1461026b57806318160ddd146102b55780631be05289146102d3575b600080fd5b6101b96004803603602081101561018d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610641565b6040518082815260200191505060405180910390f35b610211600480360360208110156101e557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610724565b6040518082815260200191505060405180910390f35b6102696004803603602081101561023d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061073c565b005b6102736107fa565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102bd610820565b6040518082815260200191505060405180910390f35b6102db61082a565b6040518082815260200191505060405180910390f35b61031d6004803603602081101561030757600080fd5b8101908080359060200190929190505050610831565b005b61034b6004803603602081101561033557600080fd5b81019080803590602001909291905050506109e6565b005b610355610c63565b005b6103996004803603602081101561036d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610e42565b6040518082815260200191505060405180910390f35b6103b7610e8b565b005b6103c1610fc6565b6040518082815260200191505060405180910390f35b6103df610fcc565b6040518082815260200191505060405180910390f35b6104376004803603602081101561040b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610fdf565b6040518082815260200191505060405180910390f35b610455610ff7565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61049f611021565b604051808215151515815260200191505060405180910390f35b6104c1611080565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61052f6004803603602081101561051957600080fd5b81019080803590602001909291905050506110a6565b005b61053961125b565b6040518082815260200191505060405180910390f35b610557611261565b6040518082815260200191505060405180910390f35b6105756112f5565b6040518082815260200191505060405180910390f35b6105936112fb565b005b61059d611316565b6040518082815260200191505060405180910390f35b6105bb61131c565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61063f6004803603602081101561061357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611341565b005b600061071d600b60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461070f6305f5e1006107016106ea600a60008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546106dc611261565b6113c790919063ffffffff16565b6106f388610e42565b61141190919063ffffffff16565b61149790919063ffffffff16565b6114e190919063ffffffff16565b9050919050565b600b6020528060005260406000206000915090505481565b610744611021565b6107b6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600460006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600154905090565b62093a8081565b3361083a611261565b600981905550610848610fcc565b600881905550600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16146109155761088b81610641565b600b60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600954600a60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b6000821161098b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260118152602001807f43616e6e6f74207769746864726177203000000000000000000000000000000081525060200191505060405180910390fd5b61099482611569565b3373ffffffffffffffffffffffffffffffffffffffff167f7084f5476618d8e60b11ef0d7d3f06914655adb8793e28ff7f018d4c76d505d5836040518082815260200191505060405180910390a25050565b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16610a27611668565b73ffffffffffffffffffffffffffffffffffffffff1614610a93576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180611f0b6021913960400191505060405180910390fd5b6000610a9d611261565b600981905550610aab610fcc565b600881905550600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610b7857610aee81610641565b600b60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600954600a60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b6006544210610ba257610b9762093a808361149790919063ffffffff16565b600781905550610c05565b6000610bb9426006546113c790919063ffffffff16565b90506000610bd26007548361141190919063ffffffff16565b9050610bfc62093a80610bee83876114e190919063ffffffff16565b61149790919063ffffffff16565b60078190555050505b42600881905550610c2262093a80426114e190919063ffffffff16565b6006819055507fde88a922e0d3b88b24e9623efeb464919c6bf9f66857a65e2bfcf2ce87a9433d826040518082815260200191505060405180910390a15050565b33610c6c611261565b600981905550610c7a610fcc565b600881905550600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614610d4757610cbd81610641565b600b60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600954600a60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b6000610d5233610641565b90506000811115610e3e576000600b60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610def3382600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166116709092919063ffffffff16565b3373ffffffffffffffffffffffffffffffffffffffff167fe2403640ba68fed3a2f88b7557551d1993f84b99bb10ff833f0cf8db0c5e0486826040518082815260200191505060405180910390a25b5050565b6000600260008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b610e93611021565b610f05576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a36000600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b60075481565b6000610fda42600654611741565b905090565b600a6020528060005260406000206000915090505481565b6000600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b6000600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611064611668565b73ffffffffffffffffffffffffffffffffffffffff1614905090565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b336110af611261565b6009819055506110bd610fcc565b600881905550600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161461118a5761110081610641565b600b60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600954600a60008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b60008211611200576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600e8152602001807f43616e6e6f74207374616b65203000000000000000000000000000000000000081525060200191505060405180910390fd5b6112098261175a565b3373ffffffffffffffffffffffffffffffffffffffff167f9e71bc8eea02a63969f509818f2dafb9254532904319f9dbda79b67bd34a5f3d836040518082815260200191505060405180910390a25050565b60085481565b60008061126c610820565b141561127c5760095490506112f2565b6112ef6112de61128a610820565b6112d06305f5e1006112c26007546112b46008546112a6610fcc565b6113c790919063ffffffff16565b61141190919063ffffffff16565b61141190919063ffffffff16565b61149790919063ffffffff16565b6009546114e190919063ffffffff16565b90505b90565b60095481565b61130c61130733610e42565b610831565b611314610c63565b565b60065481565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b611349611021565b6113bb576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b6113c48161185b565b50565b600061140983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506119a1565b905092915050565b6000808314156114245760009050611491565b600082840290508284828161143557fe5b041461148c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180611eea6021913960400191505060405180910390fd5b809150505b92915050565b60006114d983836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611a61565b905092915050565b60008082840190508381101561155f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b61157e816001546113c790919063ffffffff16565b6001819055506115d681600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546113c790919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061166533826000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166116709092919063ffffffff16565b50565b600033905090565b61173c838473ffffffffffffffffffffffffffffffffffffffff1663a9059cbb905060e01b8484604051602401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050611b27565b505050565b60008183106117505781611752565b825b905092915050565b61176f816001546114e190919063ffffffff16565b6001819055506117c781600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546114e190919063ffffffff16565b600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506118583330836000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16611d72909392919063ffffffff16565b50565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156118e1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180611ec46026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff16600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a380600360006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6000838311158290611a4e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611a135780820151818401526020810190506119f8565b50505050905090810190601f168015611a405780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b60008083118290611b0d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611ad2578082015181840152602081019050611ab7565b50505050905090810190601f168015611aff5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581611b1957fe5b049050809150509392505050565b611b468273ffffffffffffffffffffffffffffffffffffffff16611e78565b611bb8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e74726163740081525060200191505060405180910390fd5b600060608373ffffffffffffffffffffffffffffffffffffffff16836040518082805190602001908083835b60208310611c075780518252602082019150602081019050602083039250611be4565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611c69576040519150601f19603f3d011682016040523d82523d6000602084013e611c6e565b606091505b509150915081611ce6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c656481525060200191505060405180910390fd5b600081511115611d6c57808060200190516020811015611d0557600080fd5b8101908080519060200190929190505050611d6b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180611f2c602a913960400191505060405180910390fd5b5b50505050565b611e72848573ffffffffffffffffffffffffffffffffffffffff166323b872dd905060e01b858585604051602401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050611b27565b50505050565b60008060007fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47060001b9050833f9150808214158015611eba57506000801b8214155b9250505091905056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f2061646472657373536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7743616c6c6572206973206e6f742072657761726420646973747269627574696f6e5361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a265627a7a72315820757e8e5b76101b2e25a0228c935bd5290a47c2d1f15a732627ceec6eaf3b7d2d64736f6c63430005110032
[ 4, 7, 37 ]
0x4813074856374b2b38810a5652783148e3a46a74
pragma solidity 0.6.12; interface ERC20Interface { function totalSupply() external view returns(uint256); function balanceOf(address tokenOwner) external view returns(uint256); function allowance(address tokenOwner, address) external view returns(uint256); function approve(address spender, uint256 token) external returns(bool); function transfer(address to, uint256 tokens) external returns(bool); function transferFrom(address from, address to, uint256 tokens) external returns(bool); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Taker is ERC20Interface { using SafeMath for uint256; string public name; string public symbol; uint8 decimals; uint256 public _totalSupply; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; constructor() public { name = "Taker"; symbol = "TAKE"; decimals = 18; _totalSupply = 1000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view override returns(uint256) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view override returns(uint256 balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view override returns(uint256 remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint256 tokens) public override returns(bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint256 tokens) public override returns(bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint256 tokens) public override returns(bool success) { 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); return true; } }
0x608060405234801561001057600080fd5b50600436106100935760003560e01c80633eaaf86b116100665780633eaaf86b1461022157806370a082311461023f57806395d89b4114610297578063a9059cbb1461031a578063dd62ed3e1461037e57610093565b806306fdde0314610098578063095ea7b31461011b57806318160ddd1461017f57806323b872dd1461019d575b600080fd5b6100a06103f6565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100e05780820151818401526020810190506100c5565b50505050905090810190601f16801561010d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101676004803603604081101561013157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610494565b60405180821515815260200191505060405180910390f35b610187610586565b6040518082815260200191505060405180910390f35b610209600480360360608110156101b357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105d1565b60405180821515815260200191505060405180910390f35b61022961087c565b6040518082815260200191505060405180910390f35b6102816004803603602081101561025557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610882565b6040518082815260200191505060405180910390f35b61029f6108cb565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156102df5780820151818401526020810190506102c4565b50505050905090810190601f16801561030c5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103666004803603604081101561033057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610969565b60405180821515815260200191505060405180910390f35b6103e06004803603604081101561039457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610b04565b6040518082815260200191505060405180910390f35b60008054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561048c5780601f106104615761010080835404028352916020019161048c565b820191906000526020600020905b81548152906001019060200180831161046f57829003601f168201915b505050505081565b600081600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b6000600460008073ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205460035403905090565b600061062582600460008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b8b90919063ffffffff16565b600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506106f782600560008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b8b90919063ffffffff16565b600560008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506107c982600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bd590919063ffffffff16565b600460008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190509392505050565b60035481565b6000600460008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156109615780601f1061093657610100808354040283529160200191610961565b820191906000526020600020905b81548152906001019060200180831161094457829003601f168201915b505050505081565b60006109bd82600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610b8b90919063ffffffff16565b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610a5282600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610bd590919063ffffffff16565b600460008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b6000610bcd83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610c5d565b905092915050565b600080828401905083811015610c53576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b6000838311158290610d0a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610ccf578082015181840152602081019050610cb4565b50505050905090810190601f168015610cfc5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838503905080915050939250505056fea26469706673582212206e63f3a9e390eb01be385c1ec8cfebfd72de3ad1d20bd13709da0c6f2324034864736f6c634300060c0033
[ 38 ]
0x48e143b4565d25893a8e8a5f7fbfc6fb4c9b8f90
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface sbCommunityInterface { function getTokenData(address token, uint256 day) external view returns ( uint256, uint256, uint256 ); function receiveRewards(uint256 day, uint256 amount) external; function serviceAccepted(address service) external view returns (bool); function getMinerRewardPercentage() external view returns (uint256); } contract sbCommunityV2 { event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); event NewAdmin(address oldAdmin, address newAdmin); event MinerRewardsPercentageUpdated(uint256 percentage); event RewardsReceived(uint256 indexed day, uint256 amount); event ETHMined(address indexed miner, uint256 amount, uint256 indexed day); event ETHUnmined( address indexed miner, uint256 amount, uint256 indexed day ); event ERC20Mined( address indexed miner, address indexed token, uint256 amount, uint256 indexed day ); event ERC20Unmined( address indexed miner, address indexed token, uint256 amount, uint256 indexed day ); event Claimed(address indexed miner, uint256 amount, uint256 indexed day); event ServiceAdded(address indexed service, string tag); event TagAddedForService(address indexed service, string tag); using SafeMath for uint256; bool internal initDone; address internal constant ETH = address(0); string internal name; uint256 internal minerRewardPercentage; IERC20 internal strongToken; sbTokensInterface internal sbTokens; sbControllerInterface internal sbController; sbStrongPoolInterface internal sbStrongPool; sbVotesInterface internal sbVotes; address internal sbTimelock; address internal admin; address internal pendingAdmin; mapping(address => mapping(address => uint256[])) internal minerTokenDays; mapping(address => mapping(address => uint256[])) internal minerTokenAmounts; mapping(address => mapping(address => uint256[])) internal minerTokenMineSeconds; mapping(address => uint256[]) internal tokenDays; mapping(address => uint256[]) internal tokenAmounts; mapping(address => uint256[]) internal tokenMineSeconds; mapping(address => uint256) internal minerDayLastClaimedFor; mapping(uint256 => uint256) internal dayServiceRewards; address[] internal services; mapping(address => string[]) internal serviceTags; address internal superAdmin; address internal pendingSuperAdmin; uint256 internal delayDays; function setSuperAdmin() public { require(superAdmin == address(0), "superAdmin already set"); superAdmin = address(0x4B5057B2c87Ec9e7C047fb00c0E406dfF2FDaCad); } function setPendingSuperAdmin(address newPendingSuperAdmin) public { require( msg.sender == superAdmin && msg.sender != address(0), "not superAdmin" ); pendingSuperAdmin = newPendingSuperAdmin; } function acceptSuperAdmin() public { require( msg.sender == pendingSuperAdmin && msg.sender != address(0), "not pendingSuperAdmin" ); superAdmin = pendingSuperAdmin; pendingSuperAdmin = address(0); } function getSuperAdminAddressUsed() public view returns (address) { return superAdmin; } function getPendingSuperAdminAddressUsed() public view returns (address) { return pendingSuperAdmin; } function superAdminUpdateMinerRewardPercentage(uint256 percentage) external { require( msg.sender == superAdmin && msg.sender != address(0), "not superAdmin" ); require(percentage <= 100, "greater than 100"); minerRewardPercentage = percentage; emit MinerRewardsPercentageUpdated(percentage); } function setDelayDays(uint256 dayCount) public { require( msg.sender == superAdmin && msg.sender != address(0), "not superAdmin" ); require(dayCount >= 1, "zero"); delayDays = dayCount; } function getDelayDays() public view returns (uint256) { return delayDays; } function updateMinerRewardPercentage(uint256 percentage) external { require(msg.sender == sbTimelock, "not sbTimelock"); require(percentage <= 100, "greater than 100"); minerRewardPercentage = percentage; emit MinerRewardsPercentageUpdated(percentage); } function getTokenData(address token, uint256 day) external view returns ( uint256, uint256, uint256 ) { require(sbTokens.tokenAccepted(token), "invalid token"); require(day <= _getCurrentDay(), "invalid day"); return _getTokenData(token, day); } function serviceAccepted(address service) external view returns (bool) { return _serviceExists(service); } function receiveRewards(uint256 day, uint256 amount) external { require(amount > 0, "zero"); require(msg.sender == address(sbController), "not sbController"); strongToken.transferFrom(address(sbController), address(this), amount); uint256 oneHundred = 100; uint256 serviceReward = oneHundred .sub(minerRewardPercentage) .mul(amount) .div(oneHundred); (, , uint256 communityVoteSeconds) = sbVotes.getCommunityData( address(this), day ); if (communityVoteSeconds != 0 && serviceReward != 0) { dayServiceRewards[day] = serviceReward; strongToken.approve(address(sbVotes), serviceReward); sbVotes.receiveServiceRewards(day, serviceReward); } emit RewardsReceived(day, amount.sub(serviceReward)); } function getMinerRewardPercentage() external view returns (uint256) { return minerRewardPercentage; } function addService(address service, string memory tag) public { require(msg.sender == admin, "not admin"); require(sbStrongPool.serviceMinMined(service), "not min mined"); require(service != address(0), "service not zero address"); require(!_serviceExists(service), "service exists"); services.push(service); serviceTags[service].push(tag); emit ServiceAdded(service, tag); } function getServices() public view returns (address[] memory) { return services; } function getServiceTags(address service) public view returns (string[] memory) { require(_serviceExists(service), "invalid service"); return serviceTags[service]; } function addTag(address service, string memory tag) public { require(msg.sender == admin, "not admin"); require(_serviceExists(service), "invalid service"); require(!_serviceTagExists(service, tag), "tag exists"); serviceTags[service].push(tag); emit TagAddedForService(service, tag); } function setPendingAdmin(address newPendingAdmin) public { require(msg.sender == admin, "not admin"); address oldPendingAdmin = pendingAdmin; pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } function acceptAdmin() public { require( msg.sender == pendingAdmin && msg.sender != address(0), "not pendingAdmin" ); address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; admin = pendingAdmin; pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } function getAdminAddressUsed() public view returns (address) { return admin; } function getPendingAdminAddressUsed() public view returns (address) { return pendingAdmin; } function getSbControllerAddressUsed() public view returns (address) { return address(sbController); } function getStrongAddressUsed() public view returns (address) { return address(strongToken); } function getSbTokensAddressUsed() public view returns (address) { return address(sbTokens); } function getSbStrongPoolAddressUsed() public view returns (address) { return address(sbStrongPool); } function getSbVotesAddressUsed() public view returns (address) { return address(sbVotes); } function getSbTimelockAddressUsed() public view returns (address) { return sbTimelock; } function getDayServiceRewards(uint256 day) public view returns (uint256) { return dayServiceRewards[day]; } function getName() public view returns (string memory) { return name; } function getCurrentDay() public view returns (uint256) { return _getCurrentDay(); } function mineETH() public payable { require(msg.value > 0, "zero"); require(sbTokens.tokenAccepted(ETH), "invalid token"); uint256 currentDay = _getCurrentDay(); uint256 startDay = sbController.getStartDay(); uint256 MAX_YEARS = sbController.getMaxYears(); uint256 year = _getYearDayIsIn(currentDay, startDay); require(year <= MAX_YEARS, "invalid year"); require(sbStrongPool.minerMinMined(msg.sender), "not min mined"); _updateMinerTokenData(msg.sender, ETH, msg.value, true, currentDay); _updateTokenData(ETH, msg.value, true, currentDay); emit ETHMined(msg.sender, msg.value, currentDay); } function mineERC20(address token, uint256 amount) public { require(amount > 0, "zero"); require(token != ETH, "no mine ETH"); require(sbTokens.tokenAccepted(token), "invalid token"); IERC20(token).transferFrom(msg.sender, address(this), amount); uint256 currentDay = _getCurrentDay(); uint256 startDay = sbController.getStartDay(); uint256 MAX_YEARS = sbController.getMaxYears(); uint256 year = _getYearDayIsIn(currentDay, startDay); require(year <= MAX_YEARS, "invalid year"); require(sbStrongPool.minerMinMined(msg.sender), "not min mined"); _updateMinerTokenData(msg.sender, token, amount, true, currentDay); _updateTokenData(token, amount, true, currentDay); emit ERC20Mined(msg.sender, token, amount, currentDay); } function unmine(address token, uint256 amount) public { require(amount > 0, "zero"); require(sbTokens.tokenAccepted(token), "invalid token"); uint256 currentDay = _getCurrentDay(); _updateMinerTokenData(msg.sender, token, amount, false, currentDay); _updateTokenData(token, amount, false, currentDay); if (token == ETH) { msg.sender.transfer(amount); emit ETHUnmined(msg.sender, amount, currentDay); } else { IERC20(token).transfer(msg.sender, amount); emit ERC20Unmined(msg.sender, token, amount, currentDay); } } function claimAll() public { require(delayDays > 0, "zero"); uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = minerDayLastClaimedFor[msg.sender] == 0 ? sbController.getStartDay().sub(1) : minerDayLastClaimedFor[msg.sender]; require( currentDay > dayLastClaimedFor.add(delayDays), "already claimed" ); require(sbTokens.upToDate(), "need token prices"); require(sbController.upToDate(), "need rewards released"); _claim(currentDay, msg.sender, dayLastClaimedFor); } function claimUpTo(uint256 day) public { require(delayDays > 0, "zero"); require(day <= _getCurrentDay(), "invalid day"); uint256 dayLastClaimedFor = minerDayLastClaimedFor[msg.sender] == 0 ? sbController.getStartDay().sub(1) : minerDayLastClaimedFor[msg.sender]; require(day > dayLastClaimedFor.add(delayDays), "already claimed"); require(sbTokens.upToDate(), "need token prices"); require(sbController.upToDate(), "need rewards released"); _claim(day, msg.sender, dayLastClaimedFor); } function getRewardsDueAll(address miner) public view returns (uint256) { require(delayDays > 0, "zero"); uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = minerDayLastClaimedFor[miner] == 0 ? sbController.getStartDay().sub(1) : minerDayLastClaimedFor[miner]; if (!(currentDay > dayLastClaimedFor.add(delayDays))) { return 0; } require(sbTokens.upToDate(), "need token prices"); require(sbController.upToDate(), "need rewards released"); return _getRewardsDue(currentDay, miner, dayLastClaimedFor); } function getRewardsDueUpTo(uint256 day, address miner) public view returns (uint256) { require(delayDays > 0, "zero"); require(day <= _getCurrentDay(), "invalid day"); uint256 dayLastClaimedFor = minerDayLastClaimedFor[miner] == 0 ? sbController.getStartDay().sub(1) : minerDayLastClaimedFor[miner]; if (!(day > dayLastClaimedFor.add(delayDays))) { return 0; } require(sbTokens.upToDate(), "need token prices"); require(sbController.upToDate(), "need rewards released"); return _getRewardsDue(day, miner, dayLastClaimedFor); } function getMinerDayLastClaimedFor(address miner) public view returns (uint256) { return minerDayLastClaimedFor[miner] == 0 ? sbController.getStartDay().sub(1) : minerDayLastClaimedFor[miner]; } function getMinerTokenData( address miner, address token, uint256 day ) public view returns ( uint256, uint256, uint256 ) { require(sbTokens.tokenAccepted(token), "invalid token"); require(day <= _getCurrentDay(), "invalid day"); return _getMinerTokenData(miner, token, day); } function _getMinerTokenData( address miner, address token, uint256 day ) public view returns ( uint256, uint256, uint256 ) { uint256[] memory _Days = minerTokenDays[miner][token]; uint256[] memory _Amounts = minerTokenAmounts[miner][token]; uint256[] memory _UnitSeconds = minerTokenMineSeconds[miner][token]; return _get(_Days, _Amounts, _UnitSeconds, day); } function _getTokenData(address token, uint256 day) internal view returns ( uint256, uint256, uint256 ) { uint256[] memory _Days = tokenDays[token]; uint256[] memory _Amounts = tokenAmounts[token]; uint256[] memory _UnitSeconds = tokenMineSeconds[token]; return _get(_Days, _Amounts, _UnitSeconds, day); } function _updateMinerTokenData( address miner, address token, uint256 amount, bool adding, uint256 currentDay ) internal { uint256[] storage _Days = minerTokenDays[miner][token]; uint256[] storage _Amounts = minerTokenAmounts[miner][token]; uint256[] storage _UnitSeconds = minerTokenMineSeconds[miner][token]; _update(_Days, _Amounts, _UnitSeconds, amount, adding, currentDay); } function _updateTokenData( address token, uint256 amount, bool adding, uint256 currentDay ) internal { uint256[] storage _Days = tokenDays[token]; uint256[] storage _Amounts = tokenAmounts[token]; uint256[] storage _UnitSeconds = tokenMineSeconds[token]; _update(_Days, _Amounts, _UnitSeconds, amount, adding, currentDay); } function _get( uint256[] memory _Days, uint256[] memory _Amounts, uint256[] memory _UnitSeconds, uint256 day ) internal pure returns ( uint256, uint256, uint256 ) { uint256 len = _Days.length; if (len == 0) { return (day, 0, 0); } if (day < _Days[0]) { return (day, 0, 0); } uint256 lastIndex = len.sub(1); uint256 lastMinedDay = _Days[lastIndex]; if (day == lastMinedDay) { return (day, _Amounts[lastIndex], _UnitSeconds[lastIndex]); } else if (day > lastMinedDay) { return (day, _Amounts[lastIndex], _Amounts[lastIndex].mul(1 days)); } return _find(_Days, _Amounts, _UnitSeconds, day); } function _find( uint256[] memory _Days, uint256[] memory _Amounts, uint256[] memory _UnitSeconds, uint256 day ) internal pure returns ( uint256, uint256, uint256 ) { uint256 left = 0; uint256 right = _Days.length.sub(1); uint256 middle = right.add(left).div(2); while (left < right) { if (_Days[middle] == day) { return (day, _Amounts[middle], _UnitSeconds[middle]); } else if (_Days[middle] > day) { if (middle > 0 && _Days[middle.sub(1)] < day) { return ( day, _Amounts[middle.sub(1)], _Amounts[middle.sub(1)].mul(1 days) ); } if (middle == 0) { return (day, 0, 0); } right = middle.sub(1); } else if (_Days[middle] < day) { if ( middle < _Days.length.sub(1) && _Days[middle.add(1)] > day ) { return ( day, _Amounts[middle], _Amounts[middle].mul(1 days) ); } left = middle.add(1); } middle = right.add(left).div(2); } if (_Days[middle] != day) { return (day, 0, 0); } else { return (day, _Amounts[middle], _UnitSeconds[middle]); } } function _update( uint256[] storage _Days, uint256[] storage _Amounts, uint256[] storage _UnitSeconds, uint256 amount, bool adding, uint256 currentDay ) internal { uint256 len = _Days.length; uint256 secondsInADay = 1 days; uint256 secondsSinceStartOfDay = block.timestamp % secondsInADay; uint256 secondsUntilEndOfDay = secondsInADay.sub( secondsSinceStartOfDay ); if (len == 0) { if (adding) { _Days.push(currentDay); _Amounts.push(amount); _UnitSeconds.push(amount.mul(secondsUntilEndOfDay)); } else { require(false, "1: not enough mine"); } } else { uint256 lastIndex = len.sub(1); uint256 lastMinedDay = _Days[lastIndex]; uint256 lastMinedAmount = _Amounts[lastIndex]; uint256 lastUnitSeconds = _UnitSeconds[lastIndex]; uint256 newAmount; uint256 newUnitSeconds; if (lastMinedDay == currentDay) { if (adding) { newAmount = lastMinedAmount.add(amount); newUnitSeconds = lastUnitSeconds.add( amount.mul(secondsUntilEndOfDay) ); } else { require(lastMinedAmount >= amount, "2: not enough mine"); newAmount = lastMinedAmount.sub(amount); newUnitSeconds = lastUnitSeconds.sub( amount.mul(secondsUntilEndOfDay) ); } _Amounts[lastIndex] = newAmount; _UnitSeconds[lastIndex] = newUnitSeconds; } else { if (adding) { newAmount = lastMinedAmount.add(amount); newUnitSeconds = lastMinedAmount.mul(1 days).add( amount.mul(secondsUntilEndOfDay) ); } else { require(lastMinedAmount >= amount, "3: not enough mine"); newAmount = lastMinedAmount.sub(amount); newUnitSeconds = lastMinedAmount.mul(1 days).sub( amount.mul(secondsUntilEndOfDay) ); } _Days.push(currentDay); _Amounts.push(newAmount); _UnitSeconds.push(newUnitSeconds); } } } function _claim( uint256 upToDay, address miner, uint256 dayLastClaimedFor ) internal { uint256 rewards = _getRewardsDue(upToDay, miner, dayLastClaimedFor); require(rewards > 0, "no rewards"); minerDayLastClaimedFor[miner] = upToDay.sub(delayDays); strongToken.approve(address(sbStrongPool), rewards); sbStrongPool.mineFor(miner, rewards); emit Claimed(miner, rewards, _getCurrentDay()); } function _getRewardsDue( uint256 upToDay, address miner, uint256 dayLastClaimedFor ) internal view returns (uint256) { address[] memory tokens = sbTokens.getTokens(); uint256 rewards; for ( uint256 day = dayLastClaimedFor.add(1); day <= upToDay.sub(delayDays); day++ ) { uint256 communityDayMineSecondsUSD = sbController .getCommunityDayMineSecondsUSD(address(this), day); if (communityDayMineSecondsUSD == 0) { continue; } uint256 minerDayMineSecondsUSD = 0; uint256[] memory tokenPrices = sbTokens.getTokenPrices(day); for (uint256 i = 0; i < tokens.length; i++) { address token = tokens[i]; (, , uint256 minerMineSeconds) = _getMinerTokenData( miner, token, day ); uint256 amount = minerMineSeconds.mul(tokenPrices[i]).div(1e18); minerDayMineSecondsUSD = minerDayMineSecondsUSD.add(amount); } uint256 communityDayRewards = sbController .getCommunityDayRewards(address(this), day) .sub(dayServiceRewards[day]); uint256 amount = communityDayRewards .mul(minerDayMineSecondsUSD) .div(communityDayMineSecondsUSD); rewards = rewards.add(amount); } return rewards; } function _serviceExists(address service) internal view returns (bool) { return serviceTags[service].length > 0; } function _serviceTagExists(address service, string memory tag) internal view returns (bool) { for (uint256 i = 0; i < serviceTags[service].length; i++) { if ( keccak256(abi.encode(tag)) == keccak256(abi.encode(serviceTags[service][i])) ) { return true; } } return false; } function _getYearDayIsIn(uint256 day, uint256 startDay) internal pure returns (uint256) { return day.sub(startDay).div(366).add(1); // dividing by 366 makes day 1 and 365 be in year 1 } function _getCurrentDay() internal view returns (uint256) { return block.timestamp.div(1 days).add(1); } } interface sbControllerInterface { function getDayMineSecondsUSDTotal(uint256 day) external view returns (uint256); function getCommunityDayMineSecondsUSD(address community, uint256 day) external view returns (uint256); function getCommunityDayRewards(address community, uint256 day) external view returns (uint256); function getStartDay() external view returns (uint256); function getMaxYears() external view returns (uint256); function getStrongPoolDailyRewards(uint256 day) external view returns (uint256); function communityAccepted(address community) external view returns (bool); function getCommunities() external view returns (address[] memory); function upToDate() external view returns (bool); } interface sbStrongPoolInterface { function serviceMinMined(address miner) external view returns (bool); function minerMinMined(address miner) external view returns (bool); function mineFor(address miner, uint256 amount) external; function getMineData(uint256 day) external view returns ( uint256, uint256, uint256 ); function receiveRewards(uint256 day, uint256 amount) external; } interface sbTokensInterface { function getTokens() external view returns (address[] memory); function getTokenPrices(uint256 day) external view returns (uint256[] memory); function tokenAccepted(address token) external view returns (bool); function upToDate() external view returns (bool); function getTokenPrice(address token, uint256 day) external view returns (uint256); } interface sbVotesInterface { function getCommunityData(address community, uint256 day) external view returns ( uint256, uint256, uint256 ); function getPriorProposalVotes(address account, uint256 blockNumber) external view returns (uint96); function receiveServiceRewards(uint256 day, uint256 amount) external; function receiveVoterRewards(uint256 day, uint256 amount) external; function updateVotes( address staker, uint256 rawAmount, bool adding ) external; }
0x60806040526004361061023b5760003560e01c806376a8f6641161012e578063b81d29fd116100ab578063d46d17ca1161006f578063d46d17ca14610635578063e7f9cefd1461064a578063f1e5ff3e1461065f578063f36d52da1461067f578063f98260af1461069f5761023b565b8063b81d29fd146105b6578063c12eaff0146105d6578063c9ff8572146105eb578063d1058e5914610600578063d39ca7de146106155761023b565b806399ff8a2b116100f257806399ff8a2b1461052c5780639f292d761461054c578063a4bc4d7f1461056c578063aaa9a98414610581578063afd30430146105965761023b565b806376a8f6641461049357806377c76e46146104b35780638ed3ca6f146104e25780638fbc8c30146104f7578063957314e2146105175761023b565b8063426338b2116101bc5780636579bbe8116101805780636579bbe814610407578063667e3f611461040f5780636b35d2151461043c578063733fb91f1461045c57806375417851146104715761023b565b8063426338b21461037d5780634dd18bf51461039d5780635a306be0146103bd5780635a5256ef146103d25780635c6a741d146103e75761023b565b80632025dbb7116102035780632025dbb7146102e457806322817fd9146102f9578063335479a214610326578063358ff3d81461033b5780633e6968b6146103685761023b565b806304a3379f146102405780630c1803e81461026b5780630e18b6811461028d57806317d7de7c146102a25780631ba2295a146102c4575b600080fd5b34801561024c57600080fd5b506102556106bf565b6040516102629190613989565b60405180910390f35b34801561027757600080fd5b5061028b610286366004613686565b6106ce565b005b34801561029957600080fd5b5061028b6107cf565b3480156102ae57600080fd5b506102b76108b9565b6040516102629190613aac565b3480156102d057600080fd5b5061028b6102df366004613891565b61094e565b3480156102f057600080fd5b50610255610bce565b34801561030557600080fd5b5061031961031436600461362a565b610bdd565b6040516102629190613a41565b34801561033257600080fd5b50610255610cee565b34801561034757600080fd5b5061035b6103563660046138c1565b610cfd565b6040516102629190613fc4565b34801561037457600080fd5b5061035b610f4a565b34801561038957600080fd5b5061035b61039836600461362a565b610f59565b3480156103a957600080fd5b5061028b6103b836600461362a565b610fe8565b3480156103c957600080fd5b50610255611065565b3480156103de57600080fd5b50610255611074565b3480156103f357600080fd5b5061028b610402366004613724565b611083565b61028b6112bb565b34801561041b57600080fd5b5061042f61042a36600461362a565b6115c6565b6040516102629190613aa1565b34801561044857600080fd5b5061028b610457366004613724565b6115d1565b34801561046857600080fd5b5061025561198e565b34801561047d57600080fd5b5061048661199d565b60405161026291906139f4565b34801561049f57600080fd5b5061028b6104ae366004613686565b6119fe565b3480156104bf57600080fd5b506104d36104ce366004613646565b611bc4565b60405161026293929190613fdb565b3480156104ee57600080fd5b50610255611d47565b34801561050357600080fd5b5061028b610512366004613891565b611d56565b34801561052357600080fd5b5061028b611dec565b34801561053857600080fd5b5061028b610547366004613891565b611e3d565b34801561055857600080fd5b506104d3610567366004613724565b611e98565b34801561057857600080fd5b50610255611f78565b34801561058d57600080fd5b5061035b611f87565b3480156105a257600080fd5b5061035b6105b1366004613891565b611f8d565b3480156105c257600080fd5b506104d36105d1366004613646565b611f9f565b3480156105e257600080fd5b50610255612082565b3480156105f757600080fd5b50610255612091565b34801561060c57600080fd5b5061028b6120a0565b34801561062157600080fd5b5061028b61063036600461362a565b6120fa565b34801561064157600080fd5b5061035b612151565b34801561065657600080fd5b5061028b612157565b34801561066b57600080fd5b5061035b61067a36600461362a565b6121b3565b34801561068b57600080fd5b5061028b61069a3660046138f0565b6123e6565b3480156106ab57600080fd5b5061028b6106ba366004613891565b6126d2565b6003546001600160a01b031690565b6009546001600160a01b031633146107015760405162461bcd60e51b81526004016106f890613f40565b60405180910390fd5b61070a826126fc565b6107265760405162461bcd60e51b81526004016106f890613bc1565b6107308282612719565b1561074d5760405162461bcd60e51b81526004016106f890613e78565b6001600160a01b038216600090815260146020908152604082208054600181018255908352918190208351610789939190910191840190613597565b50816001600160a01b03167f6d0cef1b62b5fd4fbb8283cc973c9c2460bbbcde3e49c85f4607d034d5958773826040516107c39190613aac565b60405180910390a25050565b600a546001600160a01b0316331480156107e857503315155b6108045760405162461bcd60e51b81526004016106f890613cea565b60098054600a80546001600160a01b038082166001600160a01b03198086168217968790559092169092556040519282169390927ff9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc926108689286929116906139da565b60405180910390a1600a546040517fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9916108ad9184916001600160a01b0316906139da565b60405180910390a15050565b60018054604080516020601f600260001961010087891615020190951694909404938401819004810282018101909252828152606093909290918301828280156109445780601f1061091957610100808354040283529160200191610944565b820191906000526020600020905b81548152906001019060200180831161092757829003601f168201915b5050505050905090565b6000601754116109705760405162461bcd60e51b81526004016106f890613c14565b6109786127da565b8111156109975760405162461bcd60e51b81526004016106f890613b9c565b33600090815260116020526040812054156109c15733600090815260116020526040902054610a52565b610a526001600560009054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610a1457600080fd5b505afa158015610a28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a4c91906138a9565b906127f4565b9050610a696017548261283d90919063ffffffff16565b8211610a875760405162461bcd60e51b81526004016106f890613c95565b6004805460408051631e094d8160e21b815290516001600160a01b03909216926378253604928282019260209290829003018186803b158015610ac957600080fd5b505afa158015610add573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b019190613871565b610b1d5760405162461bcd60e51b81526004016106f890613de5565b600560009054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b158015610b6b57600080fd5b505afa158015610b7f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ba39190613871565b610bbf5760405162461bcd60e51b81526004016106f890613ee9565b610bca823383612862565b5050565b6015546001600160a01b031690565b6060610be8826126fc565b610c045760405162461bcd60e51b81526004016106f890613bc1565b6001600160a01b038216600090815260146020908152604080832080548251818502810185019093528083529193909284015b82821015610ce25760008481526020908190208301805460408051601f6002600019610100600187161502019094169390930492830185900485028101850190915281815292830182828015610cce5780601f10610ca357610100808354040283529160200191610cce565b820191906000526020600020905b815481529060010190602001808311610cb157829003601f168201915b505050505081526020019060010190610c37565b5050505090505b919050565b6016546001600160a01b031690565b60008060175411610d205760405162461bcd60e51b81526004016106f890613c14565b610d286127da565b831115610d475760405162461bcd60e51b81526004016106f890613b9c565b6001600160a01b03821660009081526011602052604081205415610d83576001600160a01b038316600090815260116020526040902054610dd6565b610dd66001600560009054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610a1457600080fd5b9050610ded6017548261283d90919063ffffffff16565b8411610dfd576000915050610f44565b6004805460408051631e094d8160e21b815290516001600160a01b03909216926378253604928282019260209290829003018186803b158015610e3f57600080fd5b505afa158015610e53573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e779190613871565b610e935760405162461bcd60e51b81526004016106f890613de5565b600560009054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b158015610ee157600080fd5b505afa158015610ef5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f199190613871565b610f355760405162461bcd60e51b81526004016106f890613ee9565b610f408484836129e3565b9150505b92915050565b6000610f546127da565b905090565b6001600160a01b03811660009081526011602052604081205415610f95576001600160a01b038216600090815260116020526040902054610f44565b610f446001600560009054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610a1457600080fd5b6009546001600160a01b031633146110125760405162461bcd60e51b81526004016106f890613f40565b600a80546001600160a01b038381166001600160a01b03198316179092556040519116907fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a9906108ad90839085906139da565b6004546001600160a01b031690565b6007546001600160a01b031690565b600081116110a35760405162461bcd60e51b81526004016106f890613c14565b6004805460405163576fbcaf60e11b81526001600160a01b039091169163aedf795e916110d291869101613989565b60206040518083038186803b1580156110ea57600080fd5b505afa1580156110fe573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111229190613871565b61113e5760405162461bcd60e51b81526004016106f890613e51565b60006111486127da565b9050611158338484600085612cbd565b6111658383600084612d22565b6001600160a01b0383166111e857604051339083156108fc029084906000818181858888f193505050501580156111a0573d6000803e3d6000fd5b5080336001600160a01b03167f88ef2f24f3715ff32630052a539436e032f89b51e6c7e343fd351598a193e00a846040516111db9190613fc4565b60405180910390a36112b6565b60405163a9059cbb60e01b81526001600160a01b0384169063a9059cbb9061121690339086906004016139c1565b602060405180830381600087803b15801561123057600080fd5b505af1158015611244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112689190613871565b5080836001600160a01b0316336001600160a01b03167f54a8170e471278d56760ff241484b47f2c71150f746849909c77bb1c40c9fe7a856040516112ad9190613fc4565b60405180910390a45b505050565b600034116112db5760405162461bcd60e51b81526004016106f890613c14565b6004805460405163576fbcaf60e11b81526001600160a01b039091169163aedf795e9161130b9160009101613989565b60206040518083038186803b15801561132357600080fd5b505afa158015611337573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061135b9190613871565b6113775760405162461bcd60e51b81526004016106f890613e51565b60006113816127da565b90506000600560009054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b1580156113d357600080fd5b505afa1580156113e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061140b91906138a9565b90506000600560009054906101000a90046001600160a01b03166001600160a01b031663b0ff52636040518163ffffffff1660e01b815260040160206040518083038186803b15801561145d57600080fd5b505afa158015611471573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061149591906138a9565b905060006114a38484612d62565b9050818111156114c55760405162461bcd60e51b81526004016106f890613d43565b60065460405163a20c845160e01b81526001600160a01b039091169063a20c8451906114f5903390600401613989565b60206040518083038186803b15801561150d57600080fd5b505afa158015611521573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115459190613871565b6115615760405162461bcd60e51b81526004016106f890613b49565b61157033600034600188612cbd565b61157e600034600187612d22565b83336001600160a01b03167f897d709bd00d87199264abc08af2a1bbe38d01946060f6cad51df59d72982d71346040516115b89190613fc4565b60405180910390a350505050565b6000610f44826126fc565b600081116115f15760405162461bcd60e51b81526004016106f890613c14565b6001600160a01b0382166116175760405162461bcd60e51b81526004016106f890613ec4565b6004805460405163576fbcaf60e11b81526001600160a01b039091169163aedf795e9161164691869101613989565b60206040518083038186803b15801561165e57600080fd5b505afa158015611672573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116969190613871565b6116b25760405162461bcd60e51b81526004016106f890613e51565b6040516323b872dd60e01b81526001600160a01b038316906323b872dd906116e29033903090869060040161399d565b602060405180830381600087803b1580156116fc57600080fd5b505af1158015611710573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117349190613871565b50600061173f6127da565b90506000600560009054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b15801561179157600080fd5b505afa1580156117a5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117c991906138a9565b90506000600560009054906101000a90046001600160a01b03166001600160a01b031663b0ff52636040518163ffffffff1660e01b815260040160206040518083038186803b15801561181b57600080fd5b505afa15801561182f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061185391906138a9565b905060006118618484612d62565b9050818111156118835760405162461bcd60e51b81526004016106f890613d43565b60065460405163a20c845160e01b81526001600160a01b039091169063a20c8451906118b3903390600401613989565b60206040518083038186803b1580156118cb57600080fd5b505afa1580156118df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119039190613871565b61191f5760405162461bcd60e51b81526004016106f890613b49565b61192d338787600188612cbd565b61193a8686600187612d22565b83866001600160a01b0316336001600160a01b03167f2b22bb5fa37289d7004304e9fec69aa9b5461b26f1a199678a30f888861072e98860405161197e9190613fc4565b60405180910390a4505050505050565b6006546001600160a01b031690565b6060601380548060200260200160405190810160405280929190818152602001828054801561094457602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116119d7575050505050905090565b6009546001600160a01b03163314611a285760405162461bcd60e51b81526004016106f890613f40565b6006546040516376d53d6160e01b81526001600160a01b03909116906376d53d6190611a58908590600401613989565b60206040518083038186803b158015611a7057600080fd5b505afa158015611a84573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611aa89190613871565b611ac45760405162461bcd60e51b81526004016106f890613b49565b6001600160a01b038216611aea5760405162461bcd60e51b81526004016106f890613f8d565b611af3826126fc565b15611b105760405162461bcd60e51b81526004016106f890613dbd565b6013805460018082019092557f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a0900180546001600160a01b0319166001600160a01b03851690811790915560009081526014602090815260408220805493840181558252908190208351611b8a939190910191840190613597565b50816001600160a01b03167fb33be4898b3eae72be50da48dea4d99c1e830cd6f31f9d534998c4fcaa91b62e826040516107c39190613aac565b6001600160a01b038084166000908152600b60209081526040808320938616835292815282822080548451818402810184019095528085529293849384936060939190830182828015611c3657602002820191906000526020600020905b815481526020019060010190808311611c22575b5050506001600160a01b03808b166000908152600c60209081526040808320938d1683529281529082902080548351818402810184019094528084529596506060959294509250830182828015611cac57602002820191906000526020600020905b815481526020019060010190808311611c98575b5050506001600160a01b03808c166000908152600d60209081526040808320938e1683529281529082902080548351818402810184019094528084529596506060959294509250830182828015611d2257602002820191906000526020600020905b815481526020019060010190808311611d0e575b50505050509050611d358383838a612d79565b95509550955050505093509350939050565b6009546001600160a01b031690565b6015546001600160a01b031633148015611d6f57503315155b611d8b5760405162461bcd60e51b81526004016106f890613e9c565b6064811115611dac5760405162461bcd60e51b81526004016106f890613f63565b60028190556040517fad92c8177533d33ec325fe51843cd29c757f7eadcd30677eb94415e5bd5ae64f90611de1908390613fc4565b60405180910390a150565b6015546001600160a01b031615611e155760405162461bcd60e51b81526004016106f890613d8d565b601580546001600160a01b031916734b5057b2c87ec9e7c047fb00c0e406dff2fdacad179055565b6015546001600160a01b031633148015611e5657503315155b611e725760405162461bcd60e51b81526004016106f890613e9c565b6001811015611e935760405162461bcd60e51b81526004016106f890613c14565b601755565b6004805460405163576fbcaf60e11b8152600092839283926001600160a01b039091169163aedf795e91611ece91899101613989565b60206040518083038186803b158015611ee657600080fd5b505afa158015611efa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f1e9190613871565b611f3a5760405162461bcd60e51b81526004016106f890613e51565b611f426127da565b841115611f615760405162461bcd60e51b81526004016106f890613b9c565b611f6b8585612e9d565b9250925092509250925092565b6008546001600160a01b031690565b60175490565b60009081526012602052604090205490565b6004805460405163576fbcaf60e11b8152600092839283926001600160a01b039091169163aedf795e91611fd591899101613989565b60206040518083038186803b158015611fed57600080fd5b505afa158015612001573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120259190613871565b6120415760405162461bcd60e51b81526004016106f890613e51565b6120496127da565b8411156120685760405162461bcd60e51b81526004016106f890613b9c565b612073868686611bc4565b92509250925093509350939050565b600a546001600160a01b031690565b6005546001600160a01b031690565b6000601754116120c25760405162461bcd60e51b81526004016106f890613c14565b60006120cc6127da565b3360009081526011602052604081205491925090156109c15733600090815260116020526040902054610a52565b6015546001600160a01b03163314801561211357503315155b61212f5760405162461bcd60e51b81526004016106f890613e9c565b601680546001600160a01b0319166001600160a01b0392909216919091179055565b60025490565b6016546001600160a01b03163314801561217057503315155b61218c5760405162461bcd60e51b81526004016106f890613d14565b60168054601580546001600160a01b03199081166001600160a01b03841617909155169055565b600080601754116121d65760405162461bcd60e51b81526004016106f890613c14565b60006121e06127da565b6001600160a01b0384166000908152601160205260408120549192509015612220576001600160a01b038416600090815260116020526040902054612273565b6122736001600560009054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610a1457600080fd5b905061228a6017548261283d90919063ffffffff16565b821161229b57600092505050610ce9565b6004805460408051631e094d8160e21b815290516001600160a01b03909216926378253604928282019260209290829003018186803b1580156122dd57600080fd5b505afa1580156122f1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123159190613871565b6123315760405162461bcd60e51b81526004016106f890613de5565b600560009054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b15801561237f57600080fd5b505afa158015612393573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123b79190613871565b6123d35760405162461bcd60e51b81526004016106f890613ee9565b6123de8285836129e3565b949350505050565b600081116124065760405162461bcd60e51b81526004016106f890613c14565b6005546001600160a01b031633146124305760405162461bcd60e51b81526004016106f890613bea565b6003546005546040516323b872dd60e01b81526001600160a01b03928316926323b872dd92612468929116903090869060040161399d565b602060405180830381600087803b15801561248257600080fd5b505af1158015612496573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124ba9190613871565b5060006064905060006124ec826124e6856124e0600254876127f490919063ffffffff16565b90612ffa565b90613034565b6007546040516303b5c12760e31b81529192506000916001600160a01b0390911690631dae09389061252490309089906004016139c1565b60606040518083038186803b15801561253c57600080fd5b505afa158015612550573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125749190613911565b92505050801580159061258657508115155b1561268a5760008581526012602052604090819020839055600354600754915163095ea7b360e01b81526001600160a01b039182169263095ea7b3926125d39291169086906004016139c1565b602060405180830381600087803b1580156125ed57600080fd5b505af1158015612601573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126259190613871565b506007546040516262983d60e91b81526001600160a01b039091169063c5307a00906126579088908690600401613fcd565b600060405180830381600087803b15801561267157600080fd5b505af1158015612685573d6000803e3d6000fd5b505050505b847f61cb44cbea389abb97c617c7d16a62235c51f27da3406d3ec3c9ac87c0d0c8266126b686856127f4565b6040516126c39190613fc4565b60405180910390a25050505050565b6008546001600160a01b03163314611d8b5760405162461bcd60e51b81526004016106f890613f18565b6001600160a01b0316600090815260146020526040902054151590565b6000805b6001600160a01b0384166000908152601460205260409020548110156127d0576001600160a01b038416600090815260146020526040902080548290811061276157fe5b9060005260206000200160405160200161277b9190613abf565b60405160208183030381529060405280519060200120836040516020016127a29190613aac565b6040516020818303038152906040528051906020012014156127c8576001915050610f44565b60010161271d565b5060009392505050565b6000610f5460016127ee4262015180613034565b9061283d565b600061283683836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613076565b9392505050565b6000828201838110156128365760405162461bcd60e51b81526004016106f890613c5e565b600061286f8484846129e3565b9050600081116128915760405162461bcd60e51b81526004016106f890613d69565b60175461289f9085906127f4565b6001600160a01b038085166000908152601160205260409081902092909255600354600654925163095ea7b360e01b81529082169263095ea7b3926128eb9291169085906004016139c1565b602060405180830381600087803b15801561290557600080fd5b505af1158015612919573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061293d9190613871565b506006546040516330d6a97560e01b81526001600160a01b03909116906330d6a9759061297090869085906004016139c1565b600060405180830381600087803b15801561298a57600080fd5b505af115801561299e573d6000803e3d6000fd5b505050506129aa6127da565b836001600160a01b03167f987d620f307ff6b94d58743cb7a7509f24071586a77759b77c2d4e29f75a2f9a836040516115b89190613fc4565b600480546040805163154d950160e31b815290516000936060936001600160a01b03169263aa6ca80892818301928792829003018186803b158015612a2757600080fd5b505afa158015612a3b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612a63919081019061374f565b9050600080612a7385600161283d565b90505b601754612a849088906127f4565b8111612cb357600554604051632a8c096960e01b81526000916001600160a01b031690632a8c096990612abd90309086906004016139c1565b60206040518083038186803b158015612ad557600080fd5b505afa158015612ae9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b0d91906138a9565b905080612b1a5750612cab565b600480546040516329baa97760e01b81526000926060926001600160a01b0316916329baa97791612b4d91889101613fc4565b60006040518083038186803b158015612b6557600080fd5b505afa158015612b79573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612ba191908101906137ed565b905060005b8651811015612c29576000878281518110612bbd57fe5b602002602001015190506000612bd48c8389611bc4565b925050506000612c0c670de0b6b3a76400006124e6878781518110612bf557fe5b602002602001015185612ffa90919063ffffffff16565b9050612c18868261283d565b95505060019092019150612ba69050565b50600084815260126020526040808220546005549151634851cd4f60e11b8152612c85926001600160a01b0316906390a39a9e90612c6d9030908b906004016139c1565b60206040518083038186803b158015610a1457600080fd5b90506000612c97856124e68487612ffa565b9050612ca3878261283d565b965050505050505b600101612a76565b5095945050505050565b6001600160a01b038086166000818152600b60209081526040808320948916808452948252808320848452600c83528184208685528352818420948452600d8352818420958452949091529020612d188383838989896130a2565b5050505050505050565b6001600160a01b0384166000908152600e60209081526040808320600f835281842060109093529220612d598383838989896130a2565b50505050505050565b600061283660016127ee61016e6124e687876127f4565b83516000908190819080612d97578460008093509350935050612e93565b87600081518110612da457fe5b6020026020010151851015612dc3578460008093509350935050612e93565b6000612dd08260016127f4565b90506000898281518110612de057fe5b6020026020010151905080871415612e295786898381518110612dff57fe5b6020026020010151898481518110612e1357fe5b6020026020010151955095509550505050612e93565b80871115612e7d5786898381518110612e3e57fe5b6020026020010151612e6f620151808c8681518110612e5957fe5b6020026020010151612ffa90919063ffffffff16565b955095509550505050612e93565b612e898a8a8a8a61334f565b9550955095505050505b9450945094915050565b6001600160a01b0382166000908152600e6020908152604080832080548251818502810185019093528083528493849360609390929091830182828015612f0357602002820191906000526020600020905b815481526020019060010190808311612eef575b5050506001600160a01b0389166000908152600f602090815260409182902080548351818402810184019094528084529596506060959294509250830182828015612f6d57602002820191906000526020600020905b815481526020019060010190808311612f59575b5050506001600160a01b038a1660009081526010602090815260409182902080548351818402810184019094528084529596506060959294509250830182828015612fd757602002820191906000526020600020905b815481526020019060010190808311612fc3575b50505050509050612fea8383838a612d79565b9550955095505050509250925092565b60008261300957506000610f44565b8282028284828161301657fe5b04146128365760405162461bcd60e51b81526004016106f890613e10565b600061283683836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250613560565b6000818484111561309a5760405162461bcd60e51b81526004016106f89190613aac565b505050900390565b8554620151804281900660006130b883836127f4565b90508361313357851561311657895460018181018c5560008c815260208082209093018890558b549182018c558b81529190912001879055876130fb8883612ffa565b8154600181018355600092835260209092209091015561312e565b60405162461bcd60e51b81526004016106f890613cbe565b613343565b60006131408560016127f4565b905060008b828154811061315057fe5b9060005260206000200154905060008b838154811061316b57fe5b9060005260206000200154905060008b848154811061318657fe5b906000526020600020015490506000808a851415613247578b156131cb576131ae848e61283d565b91506131c46131bd8e89612ffa565b849061283d565b905061320e565b8c8410156131eb5760405162461bcd60e51b81526004016106f890613b70565b6131f5848e6127f4565b915061320b6132048e89612ffa565b84906127f4565b90505b818f878154811061321b57fe5b9060005260206000200181905550808e878154811061323657fe5b60009182526020909120015561333c565b8b1561327a57613257848e61283d565b91506132736132668e89612ffa565b6127ee8662015180612ffa565b90506132c3565b8c84101561329a5760405162461bcd60e51b81526004016106f890613c32565b6132a4848e6127f4565b91506132c06132b38e89612ffa565b610a4c8662015180612ffa565b90505b8f8b90806001815401808255809150506001900390600052602060002001600090919091909150558e8290806001815401808255809150506001900390600052602060002001600090919091909150558d8190806001815401808255809150506001900390600052602060002001600090919091909150555b5050505050505b50505050505050505050565b60008060008060009050600061337060018a516127f490919063ffffffff16565b9050600061338360026124e6848661283d565b90505b8183101561352757868a828151811061339b57fe5b602002602001015114156133ca57868982815181106133b657fe5b6020026020010151898381518110612e1357fe5b868a82815181106133d757fe5b60200260200101511115613484576000811180156134115750868a6133fd8360016127f4565b8151811061340757fe5b6020026020010151105b1561345b5786896134238360016127f4565b8151811061342d57fe5b6020026020010151612e6f620151808c6134516001876127f490919063ffffffff16565b81518110612e5957fe5b806134725786600080955095509550505050612e93565b61347d8160016127f4565b9150613511565b868a828151811061349157fe5b602002602001015110156135115789516134ac9060016127f4565b811080156134d65750868a6134c283600161283d565b815181106134cc57fe5b6020026020010151115b1561350357868982815181106134e857fe5b6020026020010151612e6f620151808c8581518110612e5957fe5b61350e81600161283d565b92505b61352060026124e6848661283d565b9050613386565b868a828151811061353457fe5b6020026020010151146135535786600080955095509550505050612e93565b868982815181106133b657fe5b600081836135815760405162461bcd60e51b81526004016106f89190613aac565b50600083858161358d57fe5b0495945050505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106135d857805160ff1916838001178555613605565b82800160010185558215613605579182015b828111156136055782518255916020019190600101906135ea565b50613611929150613615565b5090565b5b808211156136115760008155600101613616565b60006020828403121561363b578081fd5b813561283681614044565b60008060006060848603121561365a578182fd5b833561366581614044565b9250602084013561367581614044565b929592945050506040919091013590565b60008060408385031215613698578182fd5b82356136a381614044565b915060208381013567ffffffffffffffff808211156136c0578384fd5b818601915086601f8301126136d3578384fd5b8135818111156136e1578485fd5b6136f3601f8201601f19168501613ff1565b91508082528784828501011115613708578485fd5b8084840185840137810190920192909252919491935090915050565b60008060408385031215613736578182fd5b823561374181614044565b946020939093013593505050565b60006020808385031215613761578182fd5b825167ffffffffffffffff811115613777578283fd5b8301601f81018513613787578283fd5b805161379a61379582614018565b613ff1565b81815283810190838501858402850186018910156137b6578687fd5b8694505b838510156137e15780516137cd81614044565b8352600194909401939185019185016137ba565b50979650505050505050565b600060208083850312156137ff578182fd5b825167ffffffffffffffff811115613815578283fd5b8301601f81018513613825578283fd5b805161383361379582614018565b818152838101908385018584028501860189101561384f578687fd5b8694505b838510156137e1578051835260019490940193918501918501613853565b600060208284031215613882578081fd5b81518015158114612836578182fd5b6000602082840312156138a2578081fd5b5035919050565b6000602082840312156138ba578081fd5b5051919050565b600080604083850312156138d3578182fd5b8235915060208301356138e581614044565b809150509250929050565b60008060408385031215613902578182fd5b50508035926020909101359150565b600080600060608486031215613925578283fd5b8351925060208401519150604084015190509250925092565b60008151808452815b8181101561396357602081850181015186830182015201613947565b818111156139745782602083870101525b50601f01601f19169290920160200192915050565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b0392831681529116602082015260400190565b6020808252825182820181905260009190848201906040850190845b81811015613a355783516001600160a01b031683529284019291840191600101613a10565b50909695505050505050565b6000602080830181845280855180835260408601915060408482028701019250838701855b82811015613a9457603f19888603018452613a8285835161393e565b94509285019290850190600101613a66565b5092979650505050505050565b901515815260200190565b600060208252612836602083018461393e565b60006020808301818452828554600180821660008114613ae65760018114613b0457613b3c565b60028304607f16855260ff1983166040890152606088019350613b3c565b60028304808652613b148a614038565b885b82811015613b325781548b820160400152908401908801613b16565b8a01604001955050505b5091979650505050505050565b6020808252600d908201526c1b9bdd081b5a5b881b5a5b9959609a1b604082015260600190565b602080825260129082015271323a206e6f7420656e6f756768206d696e6560701b604082015260600190565b6020808252600b908201526a696e76616c69642064617960a81b604082015260600190565b6020808252600f908201526e696e76616c6964207365727669636560881b604082015260600190565b60208082526010908201526f3737ba1039b121b7b73a3937b63632b960811b604082015260600190565b6020808252600490820152637a65726f60e01b604082015260600190565b602080825260129082015271333a206e6f7420656e6f756768206d696e6560701b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252600f908201526e185b1c9958591e4818db185a5b5959608a1b604082015260600190565b602080825260129082015271313a206e6f7420656e6f756768206d696e6560701b604082015260600190565b60208082526010908201526f3737ba103832b73234b733a0b236b4b760811b604082015260600190565b6020808252601590820152743737ba103832b73234b733a9bab832b920b236b4b760591b604082015260600190565b6020808252600c908201526b34b73b30b634b2103cb2b0b960a11b604082015260600190565b6020808252600a90820152696e6f207265776172647360b01b604082015260600190565b6020808252601690820152751cdd5c195c90591b5a5b88185b1c9958591e481cd95d60521b604082015260600190565b6020808252600e908201526d736572766963652065786973747360901b604082015260600190565b6020808252601190820152706e65656420746f6b656e2070726963657360781b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252600d908201526c34b73b30b634b2103a37b5b2b760991b604082015260600190565b6020808252600a90820152697461672065786973747360b01b604082015260600190565b6020808252600e908201526d3737ba1039bab832b920b236b4b760911b604082015260600190565b6020808252600b908201526a0dcde40dad2dcca408aa8960ab1b604082015260600190565b6020808252601590820152741b995959081c995dd85c991cc81c995b19585cd959605a1b604082015260600190565b6020808252600e908201526d6e6f7420736254696d656c6f636b60901b604082015260600190565b6020808252600990820152683737ba1030b236b4b760b91b604082015260600190565b60208082526010908201526f067726561746572207468616e203130360841b604082015260600190565b60208082526018908201527f73657276696365206e6f74207a65726f20616464726573730000000000000000604082015260600190565b90815260200190565b918252602082015260400190565b9283526020830191909152604082015260600190565b60405181810167ffffffffffffffff8111828210171561401057600080fd5b604052919050565b600067ffffffffffffffff82111561402e578081fd5b5060209081020190565b60009081526020902090565b6001600160a01b038116811461405957600080fd5b5056fea2646970667358221220bf53080da8ea3a573c32f5a39773393cb26071bcfa2a5d619b7eef38d9aa29c764736f6c634300060c0033
[ 0, 16, 9, 10, 5 ]
0x4a4Bb24dE2dAcF520Fdcc3C25deDD7fCe0Ae106e
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; } // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } 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) { // 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) { 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); if (originationFee > 0) { ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee); } approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user)); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x11c937fD367D75465DC211c367684d8d4520E6f9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint) { uint compBalance = 0; for(uint i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)}); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta); } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)}); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta); } } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1800000; uint public BOOST_GAS_COST = 1800000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, _user); } else { dfsFee = getFee(_closeData.daiAmount, _user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0xec504C93A40A557cC85dAc3e908E85A887438079; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy); exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxyInterface proxy = DSProxyInterface(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function logEvent( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { // swap (, destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, destAmount) = _sell(_data); } else { _data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr); destAmount = _data.srcAmount; } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompLeverage is SaverExchangeCore, CompBalance, CompoundBasicProxy { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.srcAmount -= getFee(compBalance, COMP_ADDR, address(this)); (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { ERC20(exchangeData.destAddr).transfer(msg.sender, depositAmount); } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxyInterface proxy = DSProxyInterface(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { (, uint sellAmount) = _sell(exchangeData); getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: cAddresses[0], cDebtAddr: cAddresses[1] }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } }
0x6080604052600436106102345760003560e01c806366e9a4bf1161012e578063cf786f8f116100ab578063e31f584c1161006f578063e31f584c1461055c578063e3841dad1461057c578063e9c2b6f91461058f578063ed202109146105a2578063f24ccbfe146105c25761023b565b8063cf786f8f14610336578063cfac57c7146104d8578063d0cc728914610502578063d3661fa514610517578063e304c6081461052c5761023b565b8063a46a66c9116100f2578063a46a66c914610499578063a59a9973146104ae578063acbeba61146104c3578063c11645bc146104d8578063c91d59fe146104ed5761023b565b806366e9a4bf1461042f5780636738929f146102cc578063856cba6c146104445780638c8a795814610457578063a3b8e5d11461046c5761023b565b806336569e77116101bc57806351a885c01161018057806351a885c0146103a3578063526d6461146103c357806353485907146103d85780635684e3e51461040557806364208f281461041a5761023b565b806336569e7714610336578063380d42441461034b5780634115fe6b14610360578063481c6a751461034b5780634d2ab9dc1461038e5761023b565b80632a4c0a1a116102035780632a4c0a1a146102b75780632e77468d146102cc5780632f634a90146102e1578063314b63321461030157806331d98b3f146103165761023b565b8063040141e51461024057806304c9805c1461026b578063186cab761461028d57806329f7fc9e146102a25761023b565b3661023b57005b600080fd5b34801561024c57600080fd5b506102556105d7565b60405161026291906148ad565b60405180910390f35b34801561027757600080fd5b506102806105ef565b6040516102629190614a31565b34801561029957600080fd5b506102806105f5565b3480156102ae57600080fd5b50610255610601565b3480156102c357600080fd5b50610255610619565b3480156102d857600080fd5b50610255610631565b3480156102ed57600080fd5b506102556102fc366004614607565b610649565b34801561030d57600080fd5b50610255610745565b34801561032257600080fd5b50610280610331366004614543565b61075d565b34801561034257600080fd5b5061025561091d565b34801561035757600080fd5b50610255610935565b34801561036c57600080fd5b5061038061037b366004614632565b610947565b604051610262929190614d88565b34801561039a57600080fd5b50610280610b63565b3480156103af57600080fd5b506102806103be36600461479d565b610b69565b3480156103cf57600080fd5b50610255610bc9565b3480156103e457600080fd5b506103f86103f3366004614693565b610be1565b6040516102629190614a86565b34801561041157600080fd5b50610255610c85565b34801561042657600080fd5b50610255610c9d565b61044261043d3660046146c6565b610cb5565b005b6104426104523660046146c6565b6110e5565b34801561046357600080fd5b506102556112a7565b34801561047857600080fd5b5061048c610487366004614573565b6112bf565b6040516102629190614c52565b3480156104a557600080fd5b50610255611359565b3480156104ba57600080fd5b50610255611371565b3480156104cf57600080fd5b50610255611389565b3480156104e457600080fd5b506102556113a1565b3480156104f957600080fd5b506102556113b9565b34801561050e57600080fd5b506102556113cc565b34801561052357600080fd5b506102556113e4565b34801561053857600080fd5b5061054c610547366004614543565b6113fc565b6040516102629493929190614d96565b34801561056857600080fd5b506102806105773660046147be565b611652565b61044261058a3660046146c6565b6117c3565b61044261059d3660046146c6565b611b1a565b3480156105ae57600080fd5b506102806105bd36600461479d565b611ca4565b3480156105ce57600080fd5b50610255611d86565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b61014d81565b644554482d4160d81b81565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b736b175474e89094c44da98b954eedeac495271d0f81565b7365c79fcb50ca1594b025960e539ed7a9a6d434a381565b600080836001600160a01b0316638161b120846040518263ffffffff1660e01b81526004016106789190614a31565b60206040518083038186803b15801561069057600080fd5b505afa1580156106a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106c891906144c0565b9050806001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561070357600080fd5b505afa158015610717573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061073b91906144c0565b9150505b92915050565b7325dd3f51e0c3c3ff164ddc02a8e4d65bb9cbb12d81565b604051636cb1c69b60e11b815260009081907365c79fcb50ca1594b025960e539ed7a9a6d434a39063d9638d3690610799908690600401614a31565b604080518083038186803b1580156107b057600080fd5b505afa1580156107c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107e89190614666565b604051636cb1c69b60e11b8152909250600091507335d1b3f3d7966a1dfe207aa4514c12a259a0492b9063d9638d3690610826908790600401614a31565b60a06040518083038186803b15801561083e57600080fd5b505afa158015610852573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108769190614819565b50509250505061091361090d827365c79fcb50ca1594b025960e539ed7a9a6d434a36001600160a01b031663495d32cb6040518163ffffffff1660e01b815260040160206040518083038186803b1580156108d057600080fd5b505afa1580156108e4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610908919061455b565b611d9e565b83611d9e565b925050505b919050565b7335d1b3f3d7966a1dfe207aa4514c12a259a0492b81565b600080516020614e4583398151915281565b6000806000856001600160a01b03166336569e776040518163ffffffff1660e01b815260040160206040518083038186803b15801561098557600080fd5b505afa158015610999573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109bd91906144c0565b90506000866001600160a01b0316632726b073876040518263ffffffff1660e01b81526004016109ed9190614a31565b60206040518083038186803b158015610a0557600080fd5b505afa158015610a19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a3d91906144c0565b9050600080836001600160a01b0316632424be5c88856040518363ffffffff1660e01b8152600401610a70929190614a3a565b604080518083038186803b158015610a8757600080fd5b505afa158015610a9b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610abf91906147f6565b915091506000846001600160a01b031663d9638d36896040518263ffffffff1660e01b8152600401610af19190614a31565b60a06040518083038186803b158015610b0957600080fd5b505afa158015610b1d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b419190614819565b50505091505082610b528383611d9e565b965096505050505050935093915050565b61019081565b600080610b758361075d565b9050600080610b93600080516020614e458339815191528787610947565b915091508060001415610bac576000935050505061073f565b610bbf610bb98385611ddd565b82611e05565b9695505050505050565b73637726f8b08a7abe3ae3acab01a80e2d8ddef77b81565b6060808260000151836020015184604001518560600151604051602001610c0b94939291906149ec565b60408051601f1981840301815290829052608085015160a086015160c087015160e0880151610100890151949650606095610c499590602001614d0a565b60405160208183030381529060405290508181604051602001610c6d929190614a99565b60405160208183030381529060405292505050919050565b733dfd23a6c5e8bbcfc9581d2e864a68feb6a076d381565b73ec504c93a40a557cc85dac3e908e85a88743807981565b6040516370a0823160e01b815260199081906eb3f879cb30fe243b4dfee438691c04906370a0823190610cec9030906004016148ad565b60206040518083038186803b158015610d0457600080fd5b505afa158015610d18573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d3c919061455b565b10610dc75760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f390610d73908490600401614a31565b602060405180830381600087803b158015610d8d57600080fd5b505af1158015610da1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dc59190614523565b505b604051632c2cb9fd60e01b8152600090610e51908690600080516020614e4583398151915290632c2cb9fd90610e01908490600401614a31565b60206040518083038186803b158015610e1957600080fd5b505afa158015610e2d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105bd919061455b565b90506000610e72739759a6ac90977b93b58547b4a71c78317f391a28611e28565b9050866040015182101580610e85575080155b15610eb1578187604001511115610e9e57604087018290525b610eaa87878787611b1a565b50506110de565b6000610ec1886040015184611f11565b9050818111610ed05780610ed2565b815b60405190915073ec504c93a40a557cc85dac3e908e85a887438079903480156108fc02916000818181858888f19350505050158015610f15573d6000803e3d6000fd5b506040516305b1fdb160e11b8152600080516020614e4583398151915290630b63fb6290610f60908a9073ec504c93a40a557cc85dac3e908e85a88743807990600190600401614ceb565b600060405180830381600087803b158015610f7a57600080fd5b505af1158015610f8e573d6000803e3d6000fd5b505050506060610f9d89610be1565b8888886000604051602001610fb6959493929190614abe565b60408051601f1981840301815290829052632e7ff4ef60e11b8252915073398ec7346dcd622edc5ae82352f02be94c62d11990635cffe9de9061102b9073ec504c93a40a557cc85dac3e908e85a88743807990736b175474e89094c44da98b954eedeac495271d0f908790879060040161497c565b600060405180830381600087803b15801561104557600080fd5b505af1158015611059573d6000803e3d6000fd5b50506040516305b1fdb160e11b8152600080516020614e458339815191529250630b63fb6291506110a7908b9073ec504c93a40a557cc85dac3e908e85a88743807990600090600401614ceb565b600060405180830381600087803b1580156110c157600080fd5b505af11580156110d5573d6000803e3d6000fd5b50505050505050505b5050505050565b60006110ff600080516020614e4583398151915285610649565b604051632c2cb9fd60e01b8152909150600090600080516020614e4583398151915290632c2cb9fd90611136908890600401614a31565b60206040518083038186803b15801561114e57600080fd5b505afa158015611162573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611186919061455b565b905061119785848860400151611f21565b5060006111a38761223b565b91505060006111bc826111b78489886124bb565b611f11565b90506111ca87848387612772565b47156111fe5760405132904780156108fc02916000818181858888f193505050501580156111fc573d6000803e3d6000fd5b505b735c55b921f590a89c1ebe84df170e655a82b621266001600160a01b031663d061ce5030338a888d604001518860405160200161123e9493929190614d4e565b6040516020818303038152906040526040518463ffffffff1660e01b815260040161126b93929190614930565b600060405180830381600087803b15801561128557600080fd5b505af1158015611299573d6000803e3d6000fd5b505050505050505050505050565b734ba1f38427b33b8ab7bb0490200dae1f1c36823f81565b6112c76142ef565b606080838060200190518101906112de91906145a6565b91509150818060200190518101906112f691906144dc565b606087015260408601526001600160a01b0390811660208087019190915291168452815161132b919083018101908301614727565b61010088015260e08701526001600160a01b0390811660c08701521660a08501526080840152509092915050565b731b14e8d511c9a4395425314f849bd737baf8208f81565b73398ec7346dcd622edc5ae82352f02be94c62d11981565b7319c0976f590d67707e62397c87829d896dc0f1f181565b739759a6ac90977b93b58547b4a71c78317f391a2881565b6eb3f879cb30fe243b4dfee438691c0481565b7395e6f48254609a6ee006f7d493c8e5fb97094cef81565b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b6000806000806000600080516020614e458339815191526001600160a01b0316632726b073876040518263ffffffff1660e01b815260040161143e9190614a31565b60206040518083038186803b15801561145657600080fd5b505afa15801561146a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148e91906144c0565b604051632c2cb9fd60e01b8152909150600080516020614e4583398151915290632c2cb9fd906114c2908990600401614a31565b60206040518083038186803b1580156114da57600080fd5b505afa1580156114ee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611512919061455b565b6040516309092f9760e21b81529092507335d1b3f3d7966a1dfe207aa4514c12a259a0492b90632424be5c9061154e9085908590600401614a3a565b604080518083038186803b15801561156557600080fd5b505afa158015611579573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061159d91906147f6565b604051636cb1c69b60e11b815291965094506000907335d1b3f3d7966a1dfe207aa4514c12a259a0492b9063d9638d36906115dc908690600401614a31565b60a06040518083038186803b1580156115f457600080fd5b505afa158015611608573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061162c9190614819565b50505091505061163c8582611d9e565b94506116478361075d565b935050509193509193565b60008061165e8461075d565b905060008061167c600080516020614e458339815191528888610947565b604051636cb1c69b60e11b815291935091506000907365c79fcb50ca1594b025960e539ed7a9a6d434a39063d9638d36906116bb908a90600401614a31565b604080518083038186803b1580156116d257600080fd5b505afa1580156116e6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061170a9190614666565b9150506000611726846111b76117208587612b03565b88612b27565b90506000876001600160a01b031663b3bcfa826040518163ffffffff1660e01b815260040160206040518083038186803b15801561176357600080fd5b505afa158015611777573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061179b919061455b565b601203600a0a82816117a957fe5b0490506064606382020496505050505050505b9392505050565b6040516370a0823160e01b815260199081906eb3f879cb30fe243b4dfee438691c04906370a08231906117fa9030906004016148ad565b60206040518083038186803b15801561181257600080fd5b505afa158015611826573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061184a919061455b565b106118d55760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f390611881908490600401614a31565b602060405180830381600087803b15801561189b57600080fd5b505af11580156118af573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118d39190614523565b505b604051632c2cb9fd60e01b8152600090611965908690600080516020614e4583398151915290632c2cb9fd9061190f908490600401614a31565b60206040518083038186803b15801561192757600080fd5b505afa15801561193b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061195f919061455b565b85611652565b9050600061197284611e28565b9050866040015182101580611985575080155b156119aa57818760400151111561199e57604087018290525b610eaa878787876110e5565b60006119ba886040015184611f11565b90508181116119c957806119cb565b815b60405190915073ec504c93a40a557cc85dac3e908e85a887438079903480156108fc02916000818181858888f19350505050158015611a0e573d6000803e3d6000fd5b506040516305b1fdb160e11b8152600080516020614e4583398151915290630b63fb6290611a59908a9073ec504c93a40a557cc85dac3e908e85a88743807990600190600401614ceb565b600060405180830381600087803b158015611a7357600080fd5b505af1158015611a87573d6000803e3d6000fd5b505050506060611a9689610be1565b8888886001604051602001611aaf959493929190614abe565b60408051601f19818403018152919052905073398ec7346dcd622edc5ae82352f02be94c62d119635cffe9de73ec504c93a40a557cc85dac3e908e85a887438079611af989612b32565b85856040518563ffffffff1660e01b815260040161102b949392919061497c565b6000611b34600080516020614e4583398151915285610649565b604051632c2cb9fd60e01b8152909150600090600080516020614e4583398151915290632c2cb9fd90611b6b908890600401614a31565b60206040518083038186803b158015611b8357600080fd5b505afa158015611b97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bbb919061455b565b90506000611bce86838960400151612bd4565b90506000611be1826111b78489886124bb565b6040890181905290506000611bf58961223b565b915050611c03888783613015565b4715611c375760405132904780156108fc02916000818181858888f19350505050158015611c35573d6000803e3d6000fd5b505b735c55b921f590a89c1ebe84df170e655a82b621266001600160a01b031663d061ce5030338b898e6040015187604051602001611c779493929190614d4e565b6040516020818303038152906040526040518463ffffffff1660e01b81526004016110a7939291906148db565b600080611cb08361075d565b604051636cb1c69b60e11b81529091506000907365c79fcb50ca1594b025960e539ed7a9a6d434a39063d9638d3690611ced908790600401614a31565b604080518083038186803b158015611d0457600080fd5b505afa158015611d18573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d3c9190614666565b915050600080611d5b600080516020614e458339815191528888610947565b91509150611d7b611d75611d6f8487611ddd565b85613370565b82611f11565b979650505050505050565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000676765c793fa10079d601b1b611dce611db98585612b03565b6002676765c793fa10079d601b1b5b04613388565b81611dd557fe5b049392505050565b6000670de0b6b3a7640000611dce611df58585612b03565b6002670de0b6b3a7640000611dc8565b600081611dce611e2085676765c793fa10079d601b1b612b03565b600285611dc8565b600080611e3483612b32565b90506001600160a01b03811673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611e7857733dfd23a6c5e8bbcfc9581d2e864a68feb6a076d3319150611f0b565b6040516370a0823160e01b81526001600160a01b038216906370a0823190611eb890733dfd23a6c5e8bbcfc9581d2e864a68feb6a076d3906004016148ad565b60206040518083038186803b158015611ed057600080fd5b505afa158015611ee4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f08919061455b565b91505b50919050565b8082038281111561073f57600080fd5b600080829050836001600160a01b031663b3bcfa826040518163ffffffff1660e01b815260040160206040518083038186803b158015611f6057600080fd5b505afa158015611f74573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f98919061455b565b60121461201b57836001600160a01b031663b3bcfa826040518163ffffffff1660e01b815260040160206040518083038186803b158015611fd857600080fd5b505afa158015611fec573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612010919061455b565b601203600a0a830290505b600080516020614e458339815191526345e6bdcd8661203984613398565b60000360006040518463ffffffff1660e01b815260040161205c93929190614d72565b600060405180830381600087803b15801561207657600080fd5b505af115801561208a573d6000803e3d6000fd5b50506040516313771f0760e31b8152600080516020614e458339815191529250639bb8f83891506120c390889030908690600401614ceb565b600060405180830381600087803b1580156120dd57600080fd5b505af11580156120f1573d6000803e3d6000fd5b505060405163ef693bed60e01b81526001600160a01b038716925063ef693bed915061212390309087906004016149af565b600060405180830381600087803b15801561213d57600080fd5b505af1158015612151573d6000803e3d6000fd5b5050505061215e846133ba565b1561223257836001600160a01b0316637bd2bea76040518163ffffffff1660e01b815260040160206040518083038186803b15801561219c57600080fd5b505afa1580156121b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121d491906144c0565b6001600160a01b0316632e1a7d4d846040518263ffffffff1660e01b81526004016121ff9190614a31565b600060405180830381600087803b15801561221957600080fd5b505af115801561222d573d6000803e3d6000fd5b505050505b50909392505050565b604081015181516000918291829182918291906001600160a01b031673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156122f357865161227d90613497565b6001600160a01b031687526040808801518151630d0e30db60e41b8152915173c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29263d0e30db09291600480830192600092919082900301818588803b1580156122d957600080fd5b505af11580156122ed573d6000803e3d6000fd5b50505050505b6101008701511561234a57612310876000015188604001516134de565b60006123248860000151896040015161352e565b905061233288826000613575565b90955090935091508215612348578760c0015194505b505b816123645761235a8760006138a6565b92508660a0015193505b61237687608001518860400151611ddd565b6123838860200151613abb565b10156123aa5760405162461bcd60e51b81526004016123a190614b2e565b60405180910390fd5b60006123c973c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2613abb565b11156124af576040516370a0823160e01b815273c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290632e1a7d4d9082906370a082319061240e9030906004016148ad565b602060405180830381600087803b15801561242857600080fd5b505af115801561243c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612460919061455b565b6040518263ffffffff1660e01b815260040161247c9190614a31565b600060405180830381600087803b15801561249657600080fd5b505af11580156124aa573d6000803e3d6000fd5b505050505b50919350915050915091565b6040516320eb73ed60e11b81526000906101909073637726f8b08a7abe3ae3acab01a80e2d8ddef77b906341d6e7da906124f99032906004016148ad565b60206040518083038186803b15801561251157600080fd5b505afa158015612525573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125499190614523565b15612553575061014d5b604051632cdc77ab60e21b8152731b14e8d511c9a4395425314f849bd737baf8208f9063b371deac9061258a9086906004016148ad565b60206040518083038186803b1580156125a257600080fd5b505afa1580156125b6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906125da9190614523565b1561266957604051636eeb543160e01b8152731b14e8d511c9a4395425314f849bd737baf8208f90636eeb5431906126169086906004016148ad565b60206040518083038186803b15801561262e57600080fd5b505afa158015612642573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612666919061455b565b90505b801561267e5780858161267857fe5b04612681565b60005b915083156126b857600061269c644554482d4160d81b61075d565b90506126a88582611d9e565b94506126b48386613388565b9250505b600585048211156126ca576005850491505b60405163a9059cbb60e01b8152736b175474e89094c44da98b954eedeac495271d0f9063a9059cbb906127179073322d58b9e75a6918f7e7849aee0ff09369977e089086906004016149af565b602060405180830381600087803b15801561273157600080fd5b505af1158015612745573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127699190614523565b50509392505050565b604051632726b07360e01b8152600090600080516020614e4583398151915290632726b073906127a6908890600401614a31565b60206040518083038186803b1580156127be57600080fd5b505afa1580156127d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127f691906144c0565b9050600061281a7335d1b3f3d7966a1dfe207aa4514c12a259a0492b838488613b65565b9050808411156128bd57736b175474e89094c44da98b954eedeac495271d0f63a9059cbb846128498785611f11565b6040518363ffffffff1660e01b81526004016128669291906149af565b602060405180830381600087803b15801561288057600080fd5b505af1158015612894573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128b89190614523565b508093505b604051636eb1769f60e11b8152736b175474e89094c44da98b954eedeac495271d0f9063dd62ed3e9061290a903090739759a6ac90977b93b58547b4a71c78317f391a28906004016148c1565b60206040518083038186803b15801561292257600080fd5b505afa158015612936573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061295a919061455b565b612a015760405163095ea7b360e01b8152736b175474e89094c44da98b954eedeac495271d0f9063095ea7b3906129ad90739759a6ac90977b93b58547b4a71c78317f391a2890600019906004016149af565b602060405180830381600087803b1580156129c757600080fd5b505af11580156129db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129ff9190614523565b505b604051633b4da69f60e01b8152739759a6ac90977b93b58547b4a71c78317f391a2890633b4da69f90612a3a90859088906004016149af565b600060405180830381600087803b158015612a5457600080fd5b505af1158015612a68573d6000803e3d6000fd5b50505050600080516020614e458339815191526001600160a01b03166345e6bdcd876000612aab7335d1b3f3d7966a1dfe207aa4514c12a259a0492b878b613d46565b6040518463ffffffff1660e01b8152600401612ac993929190614d72565b600060405180830381600087803b158015612ae357600080fd5b505af1158015612af7573d6000803e3d6000fd5b50505050505050505050565b6000811580612b1e57505080820282828281612b1b57fe5b04145b61073f57600080fd5b6000818381611dd557fe5b6000612b3d826133ba565b80612b64575073775787933e92b709f2a3c70aa87999696e74a9f86001600160a01b038316145b15612b84575073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee610918565b6001600160a01b038216739759a6ac90977b93b58547b4a71c78317f391a281415612bc45750736b175474e89094c44da98b954eedeac495271d0f610918565b612bcd82613f07565b9050610918565b60405163089c54b560e31b815260009081907319c0976f590d67707e62397c87829d896dc0f1f1906344e2a5a890612c10908790600401614a31565b602060405180830381600087803b158015612c2a57600080fd5b505af1158015612c3e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c62919061455b565b604051632726b07360e01b81529091506000907335d1b3f3d7966a1dfe207aa4514c12a259a0492b90636c25b34690600080516020614e4583398151915290632726b07390612cb5908b90600401614a31565b60206040518083038186803b158015612ccd57600080fd5b505afa158015612ce1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d0591906144c0565b6040518263ffffffff1660e01b8152600401612d2191906148ad565b60206040518083038186803b158015612d3957600080fd5b505afa158015612d4d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612d71919061455b565b90506000612d7f8787611ca4565b9050808510612d9657612d93816001611f11565b94505b600080516020614e458339815191526345e6bdcd886000612db8898888613f7a565b6040518463ffffffff1660e01b8152600401612dd693929190614d72565b600060405180830381600087803b158015612df057600080fd5b505af1158015612e04573d6000803e3d6000fd5b50505050600080516020614e458339815191526001600160a01b031663f9f30db68830612e3089613ffa565b6040518463ffffffff1660e01b8152600401612e4e93929190614ceb565b600060405180830381600087803b158015612e6857600080fd5b505af1158015612e7c573d6000803e3d6000fd5b5050604051634538c4eb60e01b81527335d1b3f3d7966a1dfe207aa4514c12a259a0492b9250634538c4eb9150612ecd903090739759a6ac90977b93b58547b4a71c78317f391a28906004016148c1565b60206040518083038186803b158015612ee557600080fd5b505afa158015612ef9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f1d919061455b565b612f9f576040516328ec8bf160e21b81527335d1b3f3d7966a1dfe207aa4514c12a259a0492b9063a3b22fc490612f6c90739759a6ac90977b93b58547b4a71c78317f391a28906004016148ad565b600060405180830381600087803b158015612f8657600080fd5b505af1158015612f9a573d6000803e3d6000fd5b505050505b60405163ef693bed60e01b8152739759a6ac90977b93b58547b4a71c78317f391a289063ef693bed90612fd890309089906004016149af565b600060405180830381600087803b158015612ff257600080fd5b505af1158015613006573d6000803e3d6000fd5b50969998505050505050505050565b6000613020836133ba565b156130f957826001600160a01b0316637bd2bea76040518163ffffffff1660e01b815260040160206040518083038186803b15801561305e57600080fd5b505afa158015613072573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061309691906144c0565b6001600160a01b031663d0e30db0836040518263ffffffff1660e01b81526004016000604051808303818588803b1580156130d057600080fd5b505af11580156130e4573d6000803e3d6000fd5b50505050506130f282613398565b905061310e565b61310b6131068484614011565b613398565b90505b6131948383856001600160a01b0316637bd2bea76040518163ffffffff1660e01b815260040160206040518083038186803b15801561314c57600080fd5b505afa158015613160573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061318491906144c0565b6001600160a01b03169190614093565b604051633b4da69f60e01b81526001600160a01b03841690633b4da69f906131c290309086906004016149af565b600060405180830381600087803b1580156131dc57600080fd5b505af11580156131f0573d6000803e3d6000fd5b5050604051632c2cb9fd60e01b81527335d1b3f3d7966a1dfe207aa4514c12a259a0492b925063760887039150600080516020614e4583398151915290632c2cb9fd90613241908990600401614a31565b60206040518083038186803b15801561325957600080fd5b505afa15801561326d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613291919061455b565b604051632726b07360e01b8152600080516020614e4583398151915290632726b073906132c2908a90600401614a31565b60206040518083038186803b1580156132da57600080fd5b505afa1580156132ee573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061331291906144c0565b30308660006040518763ffffffff1660e01b815260040161333896959493929190614a51565b600060405180830381600087803b15801561335257600080fd5b505af1158015613366573d6000803e3d6000fd5b5050505050505050565b600081611dce611e2085670de0b6b3a7640000612b03565b8082018281101561073f57600080fd5b8060008112156109185760405162461bcd60e51b81526004016123a190614c2c565b6000739759a6ac90977b93b58547b4a71c78317f391a286001600160a01b03831614156133e957506000610918565b816001600160a01b0316637bd2bea76040518163ffffffff1660e01b815260040160206040518083038186803b15801561342257600080fd5b505afa158015613436573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061345a91906144c0565b6001600160a01b031673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b0316141561348f57506001610918565b506000919050565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee146134c3578161073f565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc292915050565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1461352a5761352a6001600160a01b0383167395e6f48254609a6ee006f7d493c8e5fb97094cef83614093565b5050565b60006001600160a01b03831673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21461355b57504761073f565b8147111561356d57814703905061073f565b504792915050565b600080808084600181111561358657fe5b14156135a5576135a08660e001516024886040015161410e565b6135b9565b6135b98660e001516024886060015161410e565b60c0860151604051620c045f60e41b8152734ba1f38427b33b8ab7bb0490200dae1f1c36823f9162c045f0916135f291906004016148ad565b60206040518083038186803b15801561360a57600080fd5b505afa15801561361e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136429190614523565b1561364c57600094505b600061365b8760200151613abb565b60c08801516040516302f5cc7960e11b8152919250734ba1f38427b33b8ab7bb0490200dae1f1c36823f916305eb98f291613698916004016148ad565b60206040518083038186803b1580156136b057600080fd5b505afa1580156136c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136e89190614523565b1561375b578660c001516001600160a01b0316868860e0015160405161370e9190614891565b60006040518083038185875af1925050503d806000811461374b576040519150601f19603f3d011682016040523d82523d6000602084013e613750565b606091505b505080945050613760565b600093505b6040870151600090851561389757885161377990613abb565b60208a01519091506001600160a01b031673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415613885576040516370a0823160e01b815273c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290632e1a7d4d9082906370a08231906137e49030906004016148ad565b602060405180830381600087803b1580156137fe57600080fd5b505af1158015613812573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613836919061455b565b6040518263ffffffff1660e01b81526004016138529190614a31565b600060405180830381600087803b15801561386c57600080fd5b505af1158015613880573d6000803e3d6000fd5b505050505b826138938a60200151613abb565b0391505b90935091505093509350939050565b60a082015160405163e0aa279760e01b81526000917325dd3f51e0c3c3ff164ddc02a8e4d65bb9cbb12d9163e0aa2797916138e3916004016148ad565b60206040518083038186803b1580156138fb57600080fd5b505afa15801561390f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139339190614523565b61394f5760405162461bcd60e51b81526004016123a190614b00565b60a083015160408401518451600092613973926001600160a01b039092169161413a565b600083600181111561398157fe5b1415613a21578360a001516001600160a01b031663cae270b6828660000151876020015188604001516040518563ffffffff1660e01b81526004016139c8939291906149c8565b6020604051808303818588803b1580156139e157600080fd5b505af11580156139f5573d6000803e3d6000fd5b50505050506040513d601f19601f82011682018060405250810190613a1a919061455b565b9150613ab4565b8360a001516001600160a01b031663153e66e6828660000151876020015188606001516040518563ffffffff1660e01b8152600401613a62939291906149c8565b6020604051808303818588803b158015613a7b57600080fd5b505af1158015613a8f573d6000803e3d6000fd5b50505050506040513d601f19601f8201168201806040525081019061073b919061455b565b5092915050565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415613ae9575047610918565b6040516370a0823160e01b81526001600160a01b038316906370a0823190613b159030906004016148ad565b60206040518083038186803b158015613b2d57600080fd5b505afa158015613b41573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061073f919061455b565b600080856001600160a01b031663d9638d36846040518263ffffffff1660e01b8152600401613b949190614a31565b60a06040518083038186803b158015613bac57600080fd5b505afa158015613bc0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613be49190614819565b5050509150506000866001600160a01b0316632424be5c85876040518363ffffffff1660e01b8152600401613c1a929190614a3a565b604080518083038186803b158015613c3157600080fd5b505afa158015613c45573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c6991906147f6565b9150506000876001600160a01b0316636c25b346886040518263ffffffff1660e01b8152600401613c9a91906148ad565b60206040518083038186803b158015613cb257600080fd5b505afa158015613cc6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613cea919061455b565b90506000613d01613cfb8486612b03565b83611f11565b9050676765c793fa10079d601b1b8104945080613d2986676765c793fa10079d601b1b612b03565b10613d345784613d39565b846001015b9998505050505050505050565b600080846001600160a01b0316636c25b346856040518263ffffffff1660e01b8152600401613d7591906148ad565b60206040518083038186803b158015613d8d57600080fd5b505afa158015613da1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613dc5919061455b565b90506000856001600160a01b031663d9638d36856040518263ffffffff1660e01b8152600401613df59190614a31565b60a06040518083038186803b158015613e0d57600080fd5b505afa158015613e21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e459190614819565b5050509150506000866001600160a01b0316632424be5c86886040518363ffffffff1660e01b8152600401613e7b929190614a3a565b604080518083038186803b158015613e9257600080fd5b505afa158015613ea6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613eca91906147f6565b915050613edf828481613ed957fe5b04613398565b935080841115613efa57613ef281613398565b600003611d7b565b5050506000039392505050565b6000816001600160a01b0316637bd2bea76040518163ffffffff1660e01b815260040160206040518083038186803b158015613f4257600080fd5b505afa158015613f56573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061073f91906144c0565b6000613f9184676765c793fa10079d601b1b612b03565b8210156117bc57613fc183613fba613fb487676765c793fa10079d601b1b612b03565b85611f11565b81613ed957fe5b9050613fd884676765c793fa10079d601b1b612b03565b613fe28285612b03565b10613fed5780613ff2565b806001015b949350505050565b600061073f82676765c793fa10079d601b1b612b03565b60006117bc82846001600160a01b031663b3bcfa826040518163ffffffff1660e01b815260040160206040518083038186803b15801561405057600080fd5b505afa158015614064573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190614088919061455b565b601203600a0a612b03565b6140ea8363095ea7b360e01b8460006040516024016140b3929190614a15565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152614159565b6141098363095ea7b360e01b84846040516024016140b39291906149af565b505050565b81602001835110156141325760405162461bcd60e51b81526004016123a190614b65565b910160200152565b6141098363a9059cbb60e01b84846040516024016140b39291906149af565b60606141ae826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166141e89092919063ffffffff16565b80519091501561410957808060200190518101906141cc9190614523565b6141095760405162461bcd60e51b81526004016123a190614be2565b6060613ff2848460008560606141fd856142b6565b6142195760405162461bcd60e51b81526004016123a190614bab565b60006060866001600160a01b031685876040516142369190614891565b60006040518083038185875af1925050503d8060008114614273576040519150601f19603f3d011682016040523d82523d6000602084013e614278565b606091505b5091509150811561428c579150613ff29050565b80511561429c5780518082602001fd5b8360405162461bcd60e51b81526004016123a19190614a86565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590610913575050151592915050565b60405180610120016040528060006001600160a01b0316815260200160006001600160a01b0316815260200160008152602001600081526020016000815260200160006001600160a01b0316815260200160006001600160a01b0316815260200160608152602001600081525090565b803561073f81614e2c565b600082601f83011261437a578081fd5b813561438d61438882614dd8565b614db1565b91508082528360208285010111156143a457600080fd5b8060208401602084013760009082016020015292915050565b600082601f8301126143cd578081fd5b81516143db61438882614dd8565b91508082528360208285010111156143f257600080fd5b613ab4816020840160208601614dfc565b6000610120808385031215614416578182fd5b61441f81614db1565b91505061442c838361435f565b815261443b836020840161435f565b602082015260408201356040820152606082013560608201526080820135608082015261446b8360a0840161435f565b60a082015261447d8360c0840161435f565b60c082015260e082013567ffffffffffffffff81111561449c57600080fd5b6144a88482850161436a565b60e08301525061010080830135818301525092915050565b6000602082840312156144d1578081fd5b81516117bc81614e2c565b600080600080608085870312156144f1578283fd5b84516144fc81614e2c565b602086015190945061450d81614e2c565b6040860151606090960151949790965092505050565b600060208284031215614534578081fd5b815180151581146117bc578182fd5b600060208284031215614554578081fd5b5035919050565b60006020828403121561456c578081fd5b5051919050565b600060208284031215614584578081fd5b813567ffffffffffffffff81111561459a578182fd5b61073b8482850161436a565b600080604083850312156145b8578182fd5b825167ffffffffffffffff808211156145cf578384fd5b6145db868387016143bd565b935060208501519150808211156145f0578283fd5b506145fd858286016143bd565b9150509250929050565b60008060408385031215614619578182fd5b823561462481614e2c565b946020939093013593505050565b600080600060608486031215614646578283fd5b833561465181614e2c565b95602085013595506040909401359392505050565b60008060408385031215614678578182fd5b825161468381614e2c565b6020939093015192949293505050565b6000602082840312156146a4578081fd5b813567ffffffffffffffff8111156146ba578182fd5b61073b84828501614403565b600080600080608085870312156146db578182fd5b843567ffffffffffffffff8111156146f1578283fd5b6146fd87828801614403565b9450506020850135925060408501359150606085013561471c81614e2c565b939692955090935050565b600080600080600060a0868803121561473e578283fd5b85519450602086015161475081614e2c565b604087015190945061476181614e2c565b606087015190935067ffffffffffffffff81111561477d578182fd5b614789888289016143bd565b925050608086015190509295509295909350565b600080604083850312156147af578182fd5b50508035926020909101359150565b6000806000606084860312156147d2578081fd5b833592506020840135915060408401356147eb81614e2c565b809150509250925092565b60008060408385031215614808578182fd5b505080516020909101519092909150565b600080600080600060a08688031215614830578283fd5b5050835160208501516040860151606087015160809097015192989197509594509092509050565b6001600160a01b03169052565b6000815180845261487d816020860160208601614dfc565b601f01601f19169290920160200192915050565b600082516148a3818460208701614dfc565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152608060408201819052600890820152671350d1109bdbdcdd60c21b60a082015260c06060820181905260009061492790830184614865565b95945050505050565b6001600160a01b03848116825283166020820152608060408201819052600890820152674d4344526570617960c01b60a082015260c06060820181905260009061492790830184614865565b6001600160a01b0385811682528416602082015260408101839052608060608201819052600090610bbf90830184614865565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6001600160a01b0392909216825260ff16602082015260400190565b90815260200190565b9182526001600160a01b0316602082015260400190565b9586526001600160a01b039485166020870152928416604086015292166060840152608083019190915260a082015260c00190565b6000602082526117bc6020830184614865565b600060408252614aac6040830185614865565b82810360208401526149278185614865565b600060a08252614ad160a0830188614865565b60208301969096525060408101939093526001600160a01b039190911660608301521515608090910152919050565b60208082526014908201527315dc985c1c195c881a5cc81b9bdd081d985b1a5960621b604082015260600190565b6020808252601a908201527f46696e616c20616d6f756e742069736e277420636f7272656374000000000000604082015260600190565b60208082526026908201527f496e636f7272656e74206c656e6774207768696c65207772697474696e6720626040820152653cba32b9999960d11b606082015260800190565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b6020808252600c908201526b696e742d6f766572666c6f7760a01b604082015260600190565b600060208252614c66602083018451614858565b6020830151614c786040840182614858565b506040830151606083015260608301516080830152608083015160a083015260a0830151614ca960c0840182614858565b5060c0830151614cbc60e0840182614858565b5060e08301516101206101008181860152614cdb610140860184614865565b9501519301929092525090919050565b9283526001600160a01b03919091166020830152604082015260600190565b8581526001600160a01b0385811660208301528416604082015260a060608201819052600090614d3c90830185614865565b90508260808301529695505050505050565b9384526001600160a01b039290921660208401526040830152606082015260800190565b9283526020830191909152604082015260600190565b918252602082015260400190565b93845260208401929092526040830152606082015260800190565b60405181810167ffffffffffffffff81118282101715614dd057600080fd5b604052919050565b600067ffffffffffffffff821115614dee578081fd5b50601f01601f191660200190565b60005b83811015614e17578181015183820152602001614dff565b83811115614e26576000848401525b50505050565b6001600160a01b0381168114614e4157600080fd5b5056fe0000000000000000000000005ef30b9986345249bc32d8928b7ee64de9435e39a26469706673582212202764b4068457ac6858d62b00a177f0022b021321d3c50440d821ea785e76742164736f6c634300060c0033
[ 21, 4, 37, 17, 11, 8, 9, 12, 16, 5, 2 ]
0x4ae80405b877256fb46f678ec8555f24e1febe3e
pragma solidity 0.7.0; 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); } } } } 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; } } interface Events { /** * Emitted when the washout mechanism has been called. * Signifies that all tokens have been burned and all further token transfers are blocked, unless the recipient * is the contract owner. */ event Washout(); /** * Emitted when a new address is appended to the list of addresses in the contract. */ event NewAddressAppended(address newAddress); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract TokenDynAgro is Context, IERC20, Events { using SafeMath for uint256; using Address for address; address contractOwner; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; address[] private _addressList; mapping(address => bool) private _isOnAddressList; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; bool private _washedOut; /** * @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 (uint256 totalSupply_) { _name = 'DynAgro Benefit Token'; _symbol = 'DAQ'; _decimals = 2; _washedOut = false; // set the contract owner contractOwner = msg.sender; _totalSupply = totalSupply_; _balances[msg.sender] = totalSupply_; } // When attached to a function, restricts the calls to that function only to the contract owner modifier onlyOwner { require(msg.sender == contractOwner, "Only owner can call this function."); _; } /** * @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; } /** * Calls the internal _mint function to generate the given amount of tokens and add them to the total supply. * The tokens are added to the contract owner's address. */ function mint(uint256 amount) public onlyOwner returns (bool){ _mint(contractOwner, amount); return true; } /** * Sets the global variable _washedOut to true, meaning that all other functions that manage funds will not be * executing. * Also, the total supply is set to zero, so transferring tokens from the contract to users cannot happen. */ function washout() public onlyOwner returns (bool) { require(!_washedOut, "Total burn has already been executed"); _totalSupply = 0; _washedOut = true; emit Washout(); return true; } /** * Burns a given amount ot tokens from the contract owner's address. */ function burn(uint256 amount) public onlyOwner returns (bool) { _burn(contractOwner, amount); return true; } /** * The the total count of the addresses in the list of addresses of the contract. */ function getAddressCount() public view onlyOwner returns (uint count) { return _addressList.length; } /** * Get a given address at an index of the list of addresses. */ function getAddressAtRow(uint row) public view onlyOwner returns (address theAddress) { return _addressList[row]; } /** * Get the full list of addresses in the contract. */ function getAddresses() public view onlyOwner returns (address[] memory) { return _addressList; } /** * @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; } /** * Checks if the given address is already on the list of addresses, by checking if the address exists in the mapping * signifying that the address is on the list of addresses. */ function _isAddressPresent(address check) internal view returns (bool addressIsPresent) { return _isOnAddressList[check]; } /** * Appends the given address to the list of addresses in the contract, and also to the mapping signifying whether * the address is on the list. */ function _appendAddressToList(address newAddress) internal virtual { if (!_isAddressPresent(newAddress)) { _addressList.push(newAddress); _isOnAddressList[newAddress] = true; emit NewAddressAppended(newAddress); } } /** * @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"); if (recipient != contractOwner) { require(!_washedOut, "All tokes have been burned"); } _appendAddressToList(recipient); _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"); _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"); _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); } }
0x608060405234801561001057600080fd5b506004361061010b5760003560e01c806395d89b41116100a2578063a6b276c311610071578063a6b276c314610353578063a9059cbb1461035b578063b4862fe714610387578063cdbb02af146103c0578063dd62ed3e146103c85761010b565b806395d89b41146102aa578063a0712d68146102b2578063a39fac12146102cf578063a457c2d7146103275761010b565b8063313ce567116100de578063313ce5671461021d578063395093511461023b57806342966c681461026757806370a08231146102845761010b565b806306fdde0314610110578063095ea7b31461018d57806318160ddd146101cd57806323b872dd146101e7575b600080fd5b6101186103f6565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561015257818101518382015260200161013a565b50505050905090810190601f16801561017f5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101b9600480360360408110156101a357600080fd5b506001600160a01b03813516906020013561048c565b604080519115158252519081900360200190f35b6101d56104a9565b60408051918252519081900360200190f35b6101b9600480360360608110156101fd57600080fd5b506001600160a01b038135811691602081013590911690604001356104af565b610225610536565b6040805160ff9092168252519081900360200190f35b6101b96004803603604081101561025157600080fd5b506001600160a01b03813516906020013561053f565b6101b96004803603602081101561027d57600080fd5b503561058d565b6101d56004803603602081101561029a57600080fd5b50356001600160a01b03166105f5565b610118610610565b6101b9600480360360208110156102c857600080fd5b5035610671565b6102d76106d1565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156103135781810151838201526020016102fb565b505050509050019250505060405180910390f35b6101b96004803603604081101561033d57600080fd5b506001600160a01b03813516906020013561077c565b6101b96107e4565b6101b96004803603604081101561037157600080fd5b506001600160a01b0381351690602001356108b8565b6103a46004803603602081101561039d57600080fd5b50356108cc565b604080516001600160a01b039092168252519081900360200190f35b6101d561093e565b6101d5600480360360408110156103de57600080fd5b506001600160a01b038135811691602001351661098f565b60068054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104825780601f1061045757610100808354040283529160200191610482565b820191906000526020600020905b81548152906001019060200180831161046557829003601f168201915b5050505050905090565b60006104a06104996109ba565b84846109be565b50600192915050565b60055490565b60006104bc848484610aaa565b61052c846104c86109ba565b610527856040518060600160405280602881526020016110ff602891396001600160a01b038a166000908152600260205260408120906105066109ba565b6001600160a01b031681526020810191909152604001600020549190610c77565b6109be565b5060019392505050565b60085460ff1690565b60006104a061054c6109ba565b84610527856002600061055d6109ba565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490610d0e565b600080546001600160a01b031633146105d75760405162461bcd60e51b81526004018080602001828103825260228152602001806110736022913960400191505060405180910390fd5b6000546105ed906001600160a01b031683610d6f565b506001919050565b6001600160a01b031660009081526001602052604090205490565b60078054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104825780601f1061045757610100808354040283529160200191610482565b600080546001600160a01b031633146106bb5760405162461bcd60e51b81526004018080602001828103825260228152602001806110736022913960400191505060405180910390fd5b6000546105ed906001600160a01b031683610e5f565b6000546060906001600160a01b0316331461071d5760405162461bcd60e51b81526004018080602001828103825260228152602001806110736022913960400191505060405180910390fd5b600380548060200260200160405190810160405280929190818152602001828054801561048257602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610755575050505050905090565b60006104a06107896109ba565b846105278560405180606001604052806025815260200161119160259139600260006107b36109ba565b6001600160a01b03908116825260208083019390935260409182016000908120918d16815292529020549190610c77565b600080546001600160a01b0316331461082e5760405162461bcd60e51b81526004018080602001828103825260228152602001806110736022913960400191505060405180910390fd5b600854610100900460ff16156108755760405162461bcd60e51b81526004018080602001828103825260248152602001806111b66024913960400191505060405180910390fd5b600060058190556008805461ff0019166101001790556040517f9ba5d3ab76682cbda6d2e40f55511ace04d21345e8987548504076590d8845389190a150600190565b60006104a06108c56109ba565b8484610aaa565b600080546001600160a01b031633146109165760405162461bcd60e51b81526004018080602001828103825260228152602001806110736022913960400191505060405180910390fd5b6003828154811061092357fe5b6000918252602090912001546001600160a01b031692915050565b600080546001600160a01b031633146109885760405162461bcd60e51b81526004018080602001828103825260228152602001806110736022913960400191505060405180910390fd5b5060035490565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b3390565b6001600160a01b038316610a035760405162461bcd60e51b815260040180806020018281038252602481526020018061116d6024913960400191505060405180910390fd5b6001600160a01b038216610a485760405162461bcd60e51b81526004018080602001828103825260228152602001806110b76022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b038316610aef5760405162461bcd60e51b81526004018080602001828103825260258152602001806111486025913960400191505060405180910390fd5b6001600160a01b038216610b345760405162461bcd60e51b81526004018080602001828103825260238152602001806110506023913960400191505060405180910390fd5b6000546001600160a01b03838116911614610ba657600854610100900460ff1615610ba6576040805162461bcd60e51b815260206004820152601a60248201527f416c6c20746f6b65732068617665206265656e206275726e6564000000000000604482015290519081900360640190fd5b610baf82610f45565b610bec816040518060600160405280602681526020016110d9602691396001600160a01b0386166000908152600160205260409020549190610c77565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610c1b9082610d0e565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610d065760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610ccb578181015183820152602001610cb3565b50505050905090810190601f168015610cf85780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082820183811015610d68576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6001600160a01b038216610db45760405162461bcd60e51b81526004018080602001828103825260218152602001806111276021913960400191505060405180910390fd5b610df181604051806060016040528060228152602001611095602291396001600160a01b0385166000908152600160205260409020549190610c77565b6001600160a01b038316600090815260016020526040902055600554610e179082610fef565b6005556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b6001600160a01b038216610eba576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b600554610ec79082610d0e565b6005556001600160a01b038216600090815260016020526040902054610eed9082610d0e565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b610f4e81611031565b610fec576003805460018082019092557fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b0180546001600160a01b0319166001600160a01b038416908117909155600081815260046020908152604091829020805460ff19169094179093558051918252517fd9e441572cab7d3bb5556f20140a9de30db0950f73dc848bec873bae0130bd75929181900390910190a15b50565b6000610d6883836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610c77565b6001600160a01b031660009081526004602052604090205460ff169056fe45524332303a207472616e7366657220746f20746865207a65726f20616464726573734f6e6c79206f776e65722063616e2063616c6c20746869732066756e6374696f6e2e45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f546f74616c206275726e2068617320616c7265616479206265656e206578656375746564a26469706673582212206880efa6c6d19d3be985d53c076bfcda9cec1cc1dc2dc5be56c2e12083e7308864736f6c63430007000033
[ 38 ]
0x4b16df6737101d43df0db6e5306f5524fbe53a63
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; contract GovernorAlpha { /// @notice The name of this contract string public constant name = "GAMER Governor Alpha"; /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed function quorumVotes() public view returns (uint256) { return SafeMath.div(SafeMath.mul(gamer.initSupply(), 4), 100); } // 4% of GAMER /// @notice The number of votes required in order for a voter to become a proposer function proposalThreshold() public view returns (uint256) { return SafeMath.div(gamer.initSupply(), 100); } // 1% of GAMER /// @notice The maximum number of actions that can be included in a proposal function proposalMaxOperations() public pure returns (uint256) { return 10; } // 10 actions /// @notice The delay before voting on a proposal may take place, once proposed function votingDelay() public pure returns (uint256) { return 1; } // 1 block /// @notice The duration of voting on a proposal, in blocks function votingPeriod() public pure returns (uint256) { return 17280; } // ~3 days in blocks (assuming 15s blocks) /// @notice The address of the Compound Protocol Timelock TimelockInterface public timelock; /// @notice The address of the Compound governance token GAMERInterface public gamer; /// @notice The address of the Governor Guardian address public guardian; /// @notice The total number of proposals uint256 public proposalCount; struct Proposal { /// @notice Unique id for looking up a proposal uint256 id; /// @notice Creator of the proposal address proposer; /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds uint256 eta; /// @notice the ordered list of target addresses for calls to be made address[] targets; /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made uint[] values; /// @notice The ordered list of function signatures to be called string[] signatures; /// @notice The ordered list of calldata to be passed to each call bytes[] calldatas; /// @notice The block at which voting begins: holders must delegate their votes prior to this block uint256 startBlock; /// @notice The block at which voting ends: votes must be cast prior to this block uint256 endBlock; /// @notice Current number of votes in favor of this proposal uint256 forVotes; /// @notice Current number of votes in opposition to this proposal uint256 againstVotes; /// @notice Flag marking whether the proposal has been canceled bool canceled; /// @notice Flag marking whether the proposal has been executed bool executed; /// @notice Receipts of ballots for the entire set of voters mapping (address => Receipt) receipts; } /// @notice Ballot receipt record for a voter struct Receipt { /// @notice Whether or not a vote has been cast bool hasVoted; /// @notice Whether or not the voter supports the proposal bool support; /// @notice The number of votes the voter had, which were cast uint256 votes; } /// @notice Possible states that a proposal may be in enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } /// @notice The official record of all proposals ever proposed mapping (uint256 => Proposal) public proposals; /// @notice The latest proposal for each proposer mapping (address => uint256) public latestProposalIds; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the ballot struct used by the contract bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); /// @notice An event emitted when a new proposal is created event ProposalCreated(uint256 id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description); /// @notice An event emitted when a vote has been cast on a proposal event VoteCast(address voter, uint256 proposalId, bool support, uint256 votes); /// @notice An event emitted when a proposal has been canceled event ProposalCanceled(uint256 id); /// @notice An event emitted when a proposal has been queued in the Timelock event ProposalQueued(uint256 id, uint256 eta); /// @notice An event emitted when a proposal has been executed in the Timelock event ProposalExecuted(uint256 id); constructor(address timelock_, address gamer_) public { timelock = TimelockInterface(timelock_); gamer = GAMERInterface(gamer_); guardian = msg.sender; } function propose( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) public returns (uint256) { require(gamer.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); uint256 latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { ProposalState proposersLatestProposalState = state(latestProposalId); require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal"); } uint256 startBlock = add256(block.number, votingDelay()); uint256 endBlock = add256(startBlock, votingPeriod()); proposalCount++; Proposal memory newProposal = Proposal({ id: proposalCount, proposer: msg.sender, eta: 0, targets: targets, values: values, signatures: signatures, calldatas: calldatas, startBlock: startBlock, endBlock: endBlock, forVotes: 0, againstVotes: 0, canceled: false, executed: false }); proposals[newProposal.id] = newProposal; latestProposalIds[newProposal.proposer] = newProposal.id; emit ProposalCreated( newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description ); return newProposal.id; } function queue(uint256 proposalId) public { require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded"); Proposal storage proposal = proposals[proposalId]; uint256 eta = add256(block.timestamp, timelock.delay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert( proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta ); } proposal.eta = eta; emit ProposalQueued(proposalId, eta); } function _queueOrRevert( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { require(!timelock.queuedTransactions( keccak256( abi.encode( target, value, signature, data, eta ) ) ), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta" ); timelock.queueTransaction(target, value, signature, data, eta); } function execute(uint256 proposalId) public payable { require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued"); Proposal storage proposal = proposals[proposalId]; proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalExecuted(proposalId); } function cancel(uint256 proposalId) public { ProposalState state = state(proposalId); require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); Proposal storage proposal = proposals[proposalId]; require(msg.sender == guardian || gamer.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold"); proposal.canceled = true; for (uint256 i = 0; i < proposal.targets.length; i++) { timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); } emit ProposalCanceled(proposalId); } function getActions(uint256 proposalId) public view returns ( address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas ) { Proposal storage p = proposals[proposalId]; return (p.targets, p.values, p.signatures, p.calldatas); } function getReceipt(uint256 proposalId, address voter) public view returns (Receipt memory) { return proposals[proposalId].receipts[voter]; } function state(uint256 proposalId) public view returns (ProposalState) { require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); Proposal storage proposal = proposals[proposalId]; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.number <= proposal.startBlock) { return ProposalState.Pending; } else if (block.number <= proposal.endBlock) { return ProposalState.Active; } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { return ProposalState.Defeated; } else if (proposal.eta == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function castVote(uint256 proposalId, bool support) public { return _castVote(msg.sender, proposalId, support); } function castVoteBySig( uint256 proposalId, bool support, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( BALLOT_TYPEHASH, proposalId, support ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature"); return _castVote(signatory, proposalId, support); } function _castVote( address voter, uint256 proposalId, bool support ) internal { require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); Proposal storage proposal = proposals[proposalId]; Receipt storage receipt = proposal.receipts[voter]; require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); uint256 votes = gamer.getPriorVotes(voter, proposal.startBlock); if (support) { proposal.forVotes = add256(proposal.forVotes, votes); } else { proposal.againstVotes = add256(proposal.againstVotes, votes); } receipt.hasVoted = true; receipt.support = support; receipt.votes = votes; emit VoteCast(voter, proposalId, support, votes); } function __acceptAdmin() public { require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); timelock.acceptAdmin(); } function __abdicate() public { require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); guardian = address(0); } function __queueSetTimelockPendingAdmin( address newPendingAdmin, uint256 eta ) public { require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function __executeSetTimelockPendingAdmin( address newPendingAdmin, uint256 eta ) public { require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); } function add256(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "addition overflow"); return c; } function sub256(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "subtraction underflow"); return a - b; } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } interface TimelockInterface { function delay() external view returns (uint256); function GRACE_PERIOD() external view returns (uint256); function acceptAdmin() external; function queuedTransactions(bytes32 hash) external view returns (bool); function queueTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external returns (bytes32); function cancelTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external; function executeTransaction(address target, uint256 value, string calldata signature, bytes calldata data, uint256 eta) external payable returns (bytes memory); } interface GAMERInterface { function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); function initSupply() external view returns (uint256); function _acceptGov() external; } contract Timelock { using SafeMath for uint256; /// @notice An event emitted when the timelock admin changes event NewAdmin(address indexed newAdmin); /// @notice An event emitted when a new admin is staged in the timelock event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); /// @notice An event emitted when a queued transaction is cancelled event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta); /// @notice An event emitted when a queued transaction is executed event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta); /// @notice An event emitted when a new transaction is queued event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta); /// @notice the length of time after the delay has passed that a transaction can be executed uint256 public constant GRACE_PERIOD = 14 days; /// @notice the minimum length of the timelock delay uint256 public constant MINIMUM_DELAY = 2 days; // have to be present for 2 rebases /// @notice the maximum length of the timelock delay uint256 public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint256 public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor() public { /* require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); */ admin = msg.sender; delay = MINIMUM_DELAY; admin_initialized = false; } function() external payable { } /** @notice sets the delay @param delay_ the new delay */ function setDelay(uint256 delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } /// @notice sets the new admin address function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } /** @notice queues a new pendingAdmin @param pendingAdmin_ the new pendingAdmin address */ function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); // timelock not enforced prior to updating the admin. This should occur on // deployment. bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); if (admin_initialized) { require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; } bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint256) { // solium-disable-next-line security/no-block-members return block.timestamp; } } 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 Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } 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 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // 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 UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface UniswapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } 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"); } } } 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 UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair, bool isToken0 ) internal view returns (uint priceCumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = UniswapPair(pair).getReserves(); if (isToken0) { priceCumulative = UniswapPair(pair).price0CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual priceCumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; } } else { priceCumulative = UniswapPair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual priceCumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } } interface Reserves { function distributeTreasuryReward(uint256 amount) external; } contract GAMERRebaser { using SafeMath for uint256; modifier onlyGov() { require(msg.sender == gov); _; } struct Transaction { bool enabled; address destination; bytes data; } struct UniVars { uint256 gamersToUni; uint256 amountFromReserves; uint256 mintToReserves; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when maxSlippageFactor is changed event NewMaxSlippageFactor(uint256 oldSlippageFactor, uint256 newSlippageFactor); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /** * @notice Sets the treasury mint percentage of rebase */ event NewRebaseMintPercent(uint256 oldRebaseMintPerc, uint256 newRebaseMintPerc); /** * @notice Sets the reserve contract */ event NewReserveContract(address oldReserveContract, address newReserveContract); /** * @notice Sets the treasury reward ratio */ event NewTreasuryRewardRatio(uint256 oldTreasuryRewardRatio, uint256 newTreasuryRewardRatio); /** * @notice Sets the reserve contract */ event TreasuryIncreased(uint256 reservesAdded, uint256 gamersSold, uint256 gamersFromReserves, uint256 gamersToReserves); /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Governance address address public gov; /// @notice Pending Governance address address public pendingGov; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; /// @notice Percent of rebase that goes to minting for treasury building uint256 public rebaseMintPerc; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity // uint256 public constant rebaseDelay = 24 hours; uint256 public constant rebaseDelay = 24 hours; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice GAMER token address address public gamerAddress; /// @notice reserve token address public reserveToken; /// @notice Reserves vault contract address public reservesContract; /// @notice Reserves treasury reward ratio uint256 public treasuryRewardRatio; /// @notice pair for reserveToken <> GAMER address public uniswap_pair; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; // Max slippage factor when buying reserve token. Magic number based on // the fact that uniswap is a constant product. Therefore, // targeting a % max slippage can be achieved by using a single precomputed // number. i.e. 2.5% slippage is always equal to some f(maxSlippageFactor, reserves) /// @notice the maximum slippage factor when buying reserve token uint256 public maxSlippageFactor; /// @notice Whether or not this token is first in uniswap GAMER<>Reserve pair bool public isToken0; constructor( address gamerAddress_, address reserveToken_, address uniswap_factory, address reservesContract_ ) public { minRebaseTimeIntervalSec = 24 hours; rebaseWindowOffsetSec = 4 hours; // 4AM UTC rebases reservesContract = reservesContract_; (address token0, address token1) = sortTokens(gamerAddress_, reserveToken_); // used for interacting with uniswap if (token0 == gamerAddress_) { isToken0 = true; } else { isToken0 = false; } // uniswap GAMER<>Reserve pair uniswap_pair = pairFor(uniswap_factory, token0, token1); // Reserves contract is mutable reservesContract = reservesContract_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; gamerAddress = gamerAddress_; // target 10% slippage // 5.4% maxSlippageFactor = 5409258 * 10**10; // 1 DAI targetRate = 10**18; // once daily rebase, with targeting reaching peg in 20 days rebaseLag = 20; // 5% rebaseMintPerc = 5 * 10**16; // 5% deviationThreshold = 5 * 10**16; // 60 minutes rebaseWindowLengthSec = 60 * 60; // 10% treasuryRewardRatio = 10**17; // Changed in deployment scripts to facilitate protocol initiation gov = msg.sender; } /** @notice Updates slippage factor @param maxSlippageFactor_ the new slippage factor * */ function setMaxSlippageFactor(uint256 maxSlippageFactor_) public onlyGov { uint256 oldSlippageFactor = maxSlippageFactor; maxSlippageFactor = maxSlippageFactor_; emit NewMaxSlippageFactor(oldSlippageFactor, maxSlippageFactor_); } /** @notice Updates rebase mint percentage @param rebaseMintPerc_ the new rebase mint percentage * */ function setRebaseMintPerc(uint256 rebaseMintPerc_) public onlyGov { uint256 oldPerc = rebaseMintPerc; rebaseMintPerc = rebaseMintPerc_; emit NewRebaseMintPercent(oldPerc, rebaseMintPerc_); } /** @notice Updates reserve contract @param reservesContract_ the new reserve contract * */ function setReserveContract(address reservesContract_) public onlyGov { address oldReservesContract = reservesContract; reservesContract = reservesContract_; emit NewReserveContract(oldReservesContract, reservesContract_); } /** @notice sets the pendingGov * @param treasuryRewardRatio_ The treasury reward ratio of the treasury pool. */ function setTreasuryRewardRatio(uint256 treasuryRewardRatio_) external onlyGov { uint256 oldTreasuryRewardRatio = treasuryRewardRatio; treasuryRewardRatio = treasuryRewardRatio_; emit NewTreasuryRewardRatio(oldTreasuryRewardRatio, treasuryRewardRatio_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function init_twap() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activate_rebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call init_twap()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ function rebase() public { // EOA only require(msg.sender == tx.origin); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); GAMERTokenInterface gamer = GAMERTokenInterface(gamerAddress); if (positive) { require(gamer.gamersScalingFactor().mul(uint256(10**18).add(indexDelta)).div(10**18) < gamer.maxScalingFactor(), "new scaling factor will be too big"); } uint256 currSupply = gamer.totalSupply(); uint256 mintAmount; // reduce indexDelta to account for minting if (positive) { uint256 mintPerc = indexDelta.mul(rebaseMintPerc).div(10**18); indexDelta = indexDelta.sub(mintPerc); mintAmount = currSupply.mul(mintPerc).div(10**18); } else if (offPegPerc > uint256(0)) { uint256 totalTreasury = IERC20(reserveToken).balanceOf(reservesContract); if (totalTreasury > 0 && treasuryRewardRatio > 0) { uint256 treasuryReward = totalTreasury.mul(treasuryRewardRatio).div(10**18); Reserves(reservesContract).distributeTreasuryReward(treasuryReward); } } // rebase uint256 supplyAfterRebase = gamer.rebase(epoch, indexDelta, positive); assert(gamer.gamersScalingFactor() <= gamer.maxScalingFactor()); // perform actions after rebase afterRebase(mintAmount, offPegPerc); } function uniswapV2Call( address sender, uint256 amount0, uint256 amount1, bytes memory data ) public { // enforce that it is coming from uniswap require(msg.sender == uniswap_pair, "bad msg.sender"); // enforce that this contract called uniswap require(sender == address(this), "bad origin"); (UniVars memory uniVars) = abi.decode(data, (UniVars)); GAMERTokenInterface gamer = GAMERTokenInterface(gamerAddress); if (uniVars.amountFromReserves > 0) { // transfer from reserves and mint to uniswap gamer.transferFrom(reservesContract, uniswap_pair, uniVars.amountFromReserves); if (uniVars.amountFromReserves < uniVars.gamersToUni) { // if the amount from reserves > gamersToUni, we have fully paid for the DAI tokens // thus this number would be 0 so no need to mint gamer.mint(uniswap_pair, uniVars.gamersToUni.sub(uniVars.amountFromReserves)); } } else { // mint to uniswap gamer.mint(uniswap_pair, uniVars.gamersToUni); } // mint unsold to mintAmount if (uniVars.mintToReserves > 0) { gamer.mint(reservesContract, uniVars.mintToReserves); } // transfer reserve token to reserves if (isToken0) { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount1); emit TreasuryIncreased(amount1, uniVars.gamersToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } else { SafeERC20.safeTransfer(IERC20(reserveToken), reservesContract, amount0); emit TreasuryIncreased(amount0, uniVars.gamersToUni, uniVars.amountFromReserves, uniVars.mintToReserves); } } function buyReserveAndTransfer( uint256 mintAmount, uint256 offPegPerc ) internal { UniswapPair pair = UniswapPair(uniswap_pair); GAMERTokenInterface gamer = GAMERTokenInterface(gamerAddress); // get reserves (uint256 token0Reserves, uint256 token1Reserves, ) = pair.getReserves(); // check if protocol has excess gamer in the reserve uint256 excess = gamer.balanceOf(reservesContract); uint256 tokens_to_max_slippage = uniswapMaxSlippage(token0Reserves, token1Reserves, offPegPerc); UniVars memory uniVars = UniVars({ gamersToUni: tokens_to_max_slippage, // how many gamers uniswap needs amountFromReserves: excess, // how much of gamersToUni comes from reserves mintToReserves: 0 // how much gamers protocol mints to reserves }); // tries to sell all mint + excess // falls back to selling some of mint and all of excess // if all else fails, sells portion of excess // upon pair.swap, `uniswapV2Call` is called by the uniswap pair contract if (isToken0) { if (tokens_to_max_slippage > mintAmount.add(excess)) { // we already have performed a safemath check on mintAmount+excess // so we dont need to continue using it in this code path // can handle selling all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token0Reserves, token1Reserves); uniVars.gamersToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); // swap up to slippage limit, taking entire gamer reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token0Reserves, token1Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(0, buyTokens, address(this), abi.encode(uniVars)); } } } else { if (tokens_to_max_slippage > mintAmount.add(excess)) { // can handle all of reserves and mint uint256 buyTokens = getAmountOut(mintAmount + excess, token1Reserves, token0Reserves); uniVars.gamersToUni = mintAmount + excess; uniVars.amountFromReserves = excess; // call swap using entire mint amount and excess; mint 0 to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { if (tokens_to_max_slippage > excess) { // uniswap can handle entire reserves uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); // swap up to slippage limit, taking entire gamer reserves, and minting part of total uniVars.mintToReserves = mintAmount.sub((tokens_to_max_slippage - excess)); // swap up to slippage limit, taking entire gamer reserves, and minting part of total pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } else { // uniswap cant handle all of excess uint256 buyTokens = getAmountOut(tokens_to_max_slippage, token1Reserves, token0Reserves); uniVars.amountFromReserves = tokens_to_max_slippage; uniVars.mintToReserves = mintAmount; // swap up to slippage limit, taking excess - remainingExcess from reserves, and minting full amount // to reserves pair.swap(buyTokens, 0, address(this), abi.encode(uniVars)); } } } } function uniswapMaxSlippage( uint256 token0, uint256 token1, uint256 offPegPerc ) internal view returns (uint256) { if (isToken0) { if (offPegPerc >= 10**17) { // cap slippage return token0.mul(maxSlippageFactor).div(10**18); } else { // in the 5-10% off peg range, slippage is essentially 2*x (where x is percentage of pool to buy). // all we care about is not pushing below the peg, so underestimate // the amount we can sell by dividing by 3. resulting price impact // should be ~= offPegPerc * 2 / 3, which will keep us above the peg // // this is a conservative heuristic return token0.mul(offPegPerc / 3).div(10**18); } } else { if (offPegPerc >= 10**17) { return token1.mul(maxSlippageFactor).div(10**18); } else { return token1.mul(offPegPerc / 3).div(10**18); } } } /** * @notice given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset * * @param amountIn input amount of the asset * @param reserveIn reserves of the asset being sold * @param reserveOut reserves if the asset being purchased */ function getAmountOut( uint amountIn, uint reserveIn, uint reserveOut ) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } function afterRebase( uint256 mintAmount, uint256 offPegPerc ) internal { // update uniswap UniswapPair(uniswap_pair).sync(); if (mintAmount > 0) { buyReserveAndTransfer( mintAmount, offPegPerc ); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Calculates current TWAP from uniswap * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed FixedPoint.uq112x112 memory priceAverage = FixedPoint.uq112x112(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); return FixedPoint.decode144(FixedPoint.mul(priceAverage, 10**18)); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyGov { require(deviationThreshold > 0); uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyGov { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyGov { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyGov { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) private view returns (uint256, bool) { if (withinDeviationThreshold(rate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(10**18).div(targetRate), true); } else { return (targetRate.sub(rate).mul(10**18).div(targetRate), false); } } /** * @param rate The current exchange rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 rate) private view returns (bool) { uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold) .div(10 ** 18); return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold) || (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // returns sorted token addresses, used to handle return values from pairs sorted in this order 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'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyGov { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyGov { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } transactions.length--; } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyGov { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas, 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } } interface TreasuryPool { function updateNextRewards(uint256 amount) external; } contract GAMERReserves { // Token that serves as a reserve for GAMER address public reserveToken; address public gov; address public pendingGov; address public rebaser; address public gamerAddress; address public treasuryPool; /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Event emitted when TreasuryPool is changed */ event NewTreasuryPool(address oldTreasuryPool, address newTreasuryPool); /** * @notice Event emitted when rebaser is changed */ event NewRebaser(address oldRebaser, address newRebaser); modifier onlyGov() { require(msg.sender == gov); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } constructor( address reserveToken_, address gamerAddress_ ) public { reserveToken = reserveToken_; gamerAddress = gamerAddress_; gov = msg.sender; } function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; GAMERTokenInterface(gamerAddress).decreaseAllowance(oldRebaser, uint256(-1)); rebaser = rebaser_; GAMERTokenInterface(gamerAddress).approve(rebaser_, uint256(-1)); emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** * @notice lets msg.sender accept governance */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /** @notice sets the treasuryPool * @param treasuryPool_ The address of the treasury pool contract. */ function _setTreasuryPool(address treasuryPool_) external onlyGov { address oldTreasuryPool = treasuryPool; treasuryPool = treasuryPool_; emit NewTreasuryPool(oldTreasuryPool, treasuryPool_); } /// @notice Moves all tokens to a new reserve contract function migrateReserves( address newReserve, address[] memory tokens ) public onlyGov { for (uint256 i = 0; i < tokens.length; i++) { IERC20 token = IERC20(tokens[i]); uint256 bal = token.balanceOf(address(this)); SafeERC20.safeTransfer(token, newReserve, bal); } } /// @notice Gets the current amount of reserves token held by this contract function reserves() public view returns (uint256) { return IERC20(reserveToken).balanceOf(address(this)); } /// @notice Gets the current amount of reserves token held by this contract function distributeTreasuryReward(uint256 amount) public onlyRebaser { IERC20(reserveToken).transfer(treasuryPool, amount); TreasuryPool(treasuryPool).updateNextRewards(amount); } } contract GAMERGovernanceStorage { /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } contract GAMERTokenStorage { using SafeMath for uint256; /** * @dev Guard variable for re-entrancy checks. Not currently used */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved rebaser for this contract */ address public rebaser; /** * @notice Reserve address of GAMER protocol */ address public incentivizer; /** * @notice stakingPool address of GAMER protocol */ address public stakingPool; /** * @notice teamPool address of GAMER protocol */ address public teamPool; /** * @notice dev address of GAMER protocol */ address public dev; /** * @notice Total supply of GAMERs */ uint256 internal _totalSupply; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**24; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**18; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public gamersScalingFactor; mapping (address => uint256) internal _gamerBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; uint256 public initSupply; } contract GAMERTokenInterface is GAMERTokenStorage, GAMERGovernanceStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Event emitted when tokens are rebased */ event Rebase(uint256 epoch, uint256 prevGrapsScalingFactor, uint256 newGrapsScalingFactor); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Sets the rebaser contract */ event NewRebaser(address oldRebaser, address newRebaser); /** * @notice Sets the incentivizer contract */ event NewIncentivizer(address oldIncentivizer, address newIncentivizer); /** * @notice Sets the StakingPool contract */ event NewStakingPool(address oldStakingPool, address newStakingPool); /** * @notice Sets the TeamPool contract */ event NewTeamPool(address oldTeamPool, address newTeamPool); /** * @notice Sets the Dev contract */ event NewDev(address oldDev, address newDev); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); // Public functions function totalSupply() external view returns (uint256); function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function balanceOfUnderlying(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function maxScalingFactor() external view returns (uint256); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); function _setRebaser(address rebaser_) external; function _setIncentivizer(address incentivizer_) external; function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } contract GAMERGovernanceToken is GAMERTokenInterface { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "GAMER::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "GAMER::delegateBySig: invalid nonce"); require(now <= expiry, "GAMER::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "GAMER::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = _gamerBalances[delegator]; // balance of underlying GAMERs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "GAMER::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } contract GAMERToken is GAMERGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov, 'not gov'); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } modifier onlyMinter() { require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == stakingPool || msg.sender == teamPool || msg.sender == dev || msg.sender == gov, "not minter"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(gamersScalingFactor == 0, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Computes the current totalSupply */ function totalSupply() external view returns (uint256) { return _totalSupply.div(10**24/ (BASE)); } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * gamersScalingFactor // this is used to check if gamersScalingFactor will be too high to compute balances when rebasing. return uint256(-1) / initSupply; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { // increase totalSupply _totalSupply = _totalSupply.add(amount.mul(10**24/ (BASE))); // get underlying value uint256 gamerValue = amount.mul(internalDecimals).div(gamersScalingFactor); // increase initSupply initSupply = initSupply.add(gamerValue); // make sure the mint didnt push maxScalingFactor too low require(gamersScalingFactor <= _maxScalingFactor(), "max scaling factor too low"); // add balance _gamerBalances[to] = _gamerBalances[to].add(gamerValue); emit Transfer(address(0), to, amount); // add delegates to the minter _moveDelegates(address(0), _delegates[to], gamerValue); emit Mint(to, amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // underlying balance is stored in gamers, so divide by current scaling factor // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == gamersScalingFactor / 1e24; // get amount in underlying uint256 gamerValue = value.mul(internalDecimals).div(gamersScalingFactor); // sub from balance of sender _gamerBalances[msg.sender] = _gamerBalances[msg.sender].sub(gamerValue); // add to balance of receiver _gamerBalances[to] = _gamerBalances[to].add(gamerValue); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], gamerValue); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); // get value in gamers uint256 gamerValue = value.mul(internalDecimals).div(gamersScalingFactor); // sub from from _gamerBalances[from] = _gamerBalances[from].sub(gamerValue); _gamerBalances[to] = _gamerBalances[to].add(gamerValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], gamerValue); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _gamerBalances[who].mul(gamersScalingFactor).div(internalDecimals); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external view returns (uint256) { return _gamerBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /* - Governance Functions - */ /** @notice sets the rebaser * @param rebaser_ The address of the rebaser contract to use for authentication. */ function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; rebaser = rebaser_; emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the incentivizer * @param incentivizer_ The address of the incentivizer contract to use for authentication. */ function _setIncentivizer(address incentivizer_) external onlyGov { address oldIncentivizer = incentivizer; incentivizer = incentivizer_; emit NewIncentivizer(oldIncentivizer, incentivizer_); } /** @notice sets the stakingPool * @param stakingPool_ The address of the stakingPool contract to use for authentication. */ function _setStakingPool(address stakingPool_) external onlyGov { address oldStakingPool = stakingPool; stakingPool = stakingPool_; emit NewStakingPool(oldStakingPool, stakingPool_); } /** @notice sets the teamPool * @param teamPool_ The address of the teamPool contract to use for authentication. */ function _setTeamPool(address teamPool_) external onlyGov { address oldTeamPool = teamPool; teamPool = teamPool_; emit NewTeamPool(oldTeamPool, teamPool_); } /** @notice sets the dev * @param dev_ The address of the dev contract to use for authentication. */ function _setDev(address dev_) external onlyGov { address oldDev = dev; dev = dev_; emit NewDev(oldDev, dev_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /* - Extras - */ /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external onlyRebaser returns (uint256) { if (indexDelta == 0) { emit Rebase(epoch, gamersScalingFactor, gamersScalingFactor); return _totalSupply; } uint256 prevGrapsScalingFactor = gamersScalingFactor; if (!positive) { gamersScalingFactor = gamersScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); } else { uint256 newScalingFactor = gamersScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { gamersScalingFactor = newScalingFactor; } else { gamersScalingFactor = _maxScalingFactor(); } } _totalSupply = initSupply.mul(gamersScalingFactor).div(BASE); emit Rebase(epoch, prevGrapsScalingFactor, gamersScalingFactor); return _totalSupply; } } contract GAMER is GAMERToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_ ) public { require(initSupply_ > 0, "0 init supply"); super.initialize(name_, symbol_, decimals_); initSupply = initSupply_.mul(10**24/ (BASE)); _totalSupply = initSupply; gamersScalingFactor = BASE; _gamerBalances[initial_owner] = initSupply_.mul(10**24 / (BASE)); // owner renounces ownership after deployment as they need to set // rebaser and incentivizer // gov = gov_; } }
0x6080604052600436106101ac5760003560e01c8063452a9320116100ec578063d33219b41161008a578063ddf0b00911610064578063ddf0b00914610473578063deaaa7cc14610493578063e23a9a52146104a8578063fe0d94c1146104d5576101ac565b8063d33219b414610429578063da35c6641461043e578063da95691a14610453576101ac565b80637bdbe4d0116100c65780637bdbe4d0146103ca57806391500671146103df578063b58131b0146103ff578063b9a6196114610414576101ac565b8063452a9320146103735780634634c61f14610395578063760fbc13146103b5576101ac565b806320606b7011610159578063328dd98211610133578063328dd982146102e15780633932abb1146103115780633e4f49e61461032657806340e58ee514610353576101ac565b806320606b701461029757806321f43e42146102ac57806324bc1a64146102cc576101ac565b806315373e3d1161018a57806315373e3d1461023357806317977c611461025557806319ab81e914610275576101ac565b8063013cf08b146101b157806302a251a3146101ef57806306fdde0314610211575b600080fd5b3480156101bd57600080fd5b506101d16101cc366004612c31565b6104e8565b6040516101e699989796959493929190613f53565b60405180910390f35b3480156101fb57600080fd5b5061020461054e565b6040516101e69190613c7d565b34801561021d57600080fd5b50610226610555565b6040516101e69190613d2c565b34801561023f57600080fd5b5061025361024e366004612c7f565b61058e565b005b34801561026157600080fd5b50610204610270366004612a74565b61059d565b34801561028157600080fd5b5061028a6105af565b6040516101e69190613d10565b3480156102a357600080fd5b506102046105cb565b3480156102b857600080fd5b506102536102c7366004612a9a565b6105e2565b3480156102d857600080fd5b5061020461071b565b3480156102ed57600080fd5b506103016102fc366004612c31565b6107d6565b6040516101e69493929190613c30565b34801561031d57600080fd5b50610204610aae565b34801561033257600080fd5b50610346610341366004612c31565b610ab3565b6040516101e69190613d1e565b34801561035f57600080fd5b5061025361036e366004612c31565b610c75565b34801561037f57600080fd5b50610388610f5b565b6040516101e69190613ada565b3480156103a157600080fd5b506102536103b0366004612caf565b610f77565b3480156103c157600080fd5b50610253611159565b3480156103d657600080fd5b506102046111d4565b3480156103eb57600080fd5b506102536103fa366004612a9a565b6111d9565b34801561040b57600080fd5b506102046112e2565b34801561042057600080fd5b50610253611387565b34801561043557600080fd5b5061028a611459565b34801561044a57600080fd5b50610204611475565b34801561045f57600080fd5b5061020461046e366004612ad4565b61147b565b34801561047f57600080fd5b5061025361048e366004612c31565b61197e565b34801561049f57600080fd5b50610204611c71565b3480156104b457600080fd5b506104c86104c3366004612c4f565b611c7d565b6040516101e69190613e9d565b6102536104e3366004612c31565b611cee565b6004602052600090815260409020805460018201546002830154600784015460088501546009860154600a870154600b90970154959673ffffffffffffffffffffffffffffffffffffffff90951695939492939192909160ff8082169161010090041689565b6143805b90565b6040518060400160405280601481526020017f47414d455220476f7665726e6f7220416c70686100000000000000000000000081525081565b610599338383611f22565b5050565b60056020526000908152604090205481565b60015473ffffffffffffffffffffffffffffffffffffffff1681565b6040516105d790613ac4565b604051809103902081565b60025473ffffffffffffffffffffffffffffffffffffffff16331461063c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613d6d565b60405180910390fd5b6000805460405173ffffffffffffffffffffffffffffffffffffffff90911691630825f38f91839190610673908790602001613ada565b604051602081830303815290604052856040518563ffffffff1660e01b81526004016106a29493929190613b03565b600060405180830381600087803b1580156106bc57600080fd5b505af11580156106d0573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526107169190810190612bfc565b505050565b60006107d16107ca600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166397d63f936040518163ffffffff1660e01b815260040160206040518083038186803b15801561078b57600080fd5b505afa15801561079f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506107c39190810190612bde565b6004612160565b60646121bb565b905090565b6060806060806000600460008781526020019081526020016000209050806003018160040182600501836006018380548060200260200160405190810160405280929190818152602001828054801561086557602002820191906000526020600020905b815473ffffffffffffffffffffffffffffffffffffffff16815260019091019060200180831161083a575b50505050509350828054806020026020016040519081016040528092919081815260200182805480156108b757602002820191906000526020600020905b8154815260200190600101908083116108a3575b5050505050925081805480602002602001604051908101604052809291908181526020016000905b828210156109a85760008481526020908190208301805460408051601f60027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff6101006001871615020190941693909304928301859004850281018501909152818152928301828280156109945780601f1061096957610100808354040283529160200191610994565b820191906000526020600020905b81548152906001019060200180831161097757829003601f168201915b5050505050815260200190600101906108df565b50505050915080805480602002602001604051908101604052809291908181526020016000905b82821015610a985760008481526020908190208301805460408051601f60027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff610100600187161502019094169390930492830185900485028101850190915281815292830182828015610a845780601f10610a5957610100808354040283529160200191610a84565b820191906000526020600020905b815481529060010190602001808311610a6757829003601f168201915b5050505050815260200190600101906109cf565b5050505090509450945094509450509193509193565b600190565b60008160035410158015610ac75750600082115b610afd576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613d7d565b6000828152600460205260409020600b81015460ff1615610b22576002915050610c70565b80600701544311610b37576000915050610c70565b80600801544311610b4c576001915050610c70565b80600a01548160090154111580610b6d5750610b6661071b565b8160090154105b15610b7c576003915050610c70565b6002810154610b8f576004915050610c70565b600b810154610100900460ff1615610bab576007915050610c70565b6002810154600054604080517fc1a287e20000000000000000000000000000000000000000000000000000000081529051610c5a939273ffffffffffffffffffffffffffffffffffffffff169163c1a287e2916004808301926020929190829003018186803b158015610c1d57600080fd5b505afa158015610c31573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610c559190810190612bde565b6121fd565b4210610c6a576006915050610c70565b60059150505b919050565b6000610c8082610ab3565b90506007816007811115610c9057fe5b1415610cc8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e5d565b600082815260046020526040902060025473ffffffffffffffffffffffffffffffffffffffff16331480610da45750610cff6112e2565b600180548382015473ffffffffffffffffffffffffffffffffffffffff9182169263782d6fe19290911690610d3590439061223c565b6040518363ffffffff1660e01b8152600401610d52929190613b52565b60206040518083038186803b158015610d6a57600080fd5b505afa158015610d7e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250610da29190810190612bde565b105b610dda576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613dfd565b600b810180547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016600117905560005b6003820154811015610f1e5760005460038301805473ffffffffffffffffffffffffffffffffffffffff9092169163591fcdfe919084908110610e4957fe5b60009182526020909120015460048501805473ffffffffffffffffffffffffffffffffffffffff9092169185908110610e7e57fe5b9060005260206000200154856005018581548110610e9857fe5b90600052602060002001866006018681548110610eb157fe5b9060005260206000200187600201546040518663ffffffff1660e01b8152600401610ee0959493929190613bef565b600060405180830381600087803b158015610efa57600080fd5b505af1158015610f0e573d6000803e3d6000fd5b505060019092019150610e0a9050565b507f789cf55be980739dad1d0699b93b58e806b51c9d96619bfa8fe0a28abaa7b30c83604051610f4e9190613c7d565b60405180910390a1505050565b60025473ffffffffffffffffffffffffffffffffffffffff1681565b6000604051610f8590613ac4565b60408051918290038220828201909152601482527f47414d455220476f7665726e6f7220416c7068610000000000000000000000006020909201919091527f6c7f595e5d7cd473ebc0afb41a71fd00b7c8c92af64e54720f461a4cf958f1f4610fec61227e565b306040516020016110009493929190613c8b565b604051602081830303815290604052805190602001209050600060405161102690613acf565b60405190819003812061103f9189908990602001613cc0565b6040516020818303038152906040528051906020012090506000828260405160200161106c929190613a93565b6040516020818303038152906040528051906020012090506000600182888888604051600081526020016040526040516110a99493929190613ce8565b6020604051602081039080840390855afa1580156110cb573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff8116611143576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e3d565b61114e818a8a611f22565b505050505050505050565b60025473ffffffffffffffffffffffffffffffffffffffff1633146111aa576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e8d565b600280547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b600a90565b60025473ffffffffffffffffffffffffffffffffffffffff16331461122a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613dad565b6000805460405173ffffffffffffffffffffffffffffffffffffffff90911691633a66f90191839190611261908790602001613ada565b604051602081830303815290604052856040518563ffffffff1660e01b81526004016112909493929190613b03565b602060405180830381600087803b1580156112aa57600080fd5b505af11580156112be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506107169190810190612bde565b60006107d1600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166397d63f936040518163ffffffff1660e01b815260040160206040518083038186803b15801561134f57600080fd5b505afa158015611363573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506107ca9190810190612bde565b60025473ffffffffffffffffffffffffffffffffffffffff1633146113d8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613d3d565b60008054604080517f0e18b681000000000000000000000000000000000000000000000000000000008152905173ffffffffffffffffffffffffffffffffffffffff90921692630e18b6819260048084019382900301818387803b15801561143f57600080fd5b505af1158015611453573d6000803e3d6000fd5b50505050565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b60035481565b60006114856112e2565b6001805473ffffffffffffffffffffffffffffffffffffffff169063782d6fe19033906114b390439061223c565b6040518363ffffffff1660e01b81526004016114d0929190613ae8565b60206040518083038186803b1580156114e857600080fd5b505afa1580156114fc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506115209190810190612bde565b11611557576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e2d565b84518651148015611569575083518651145b8015611576575082518651145b6115ac576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613ddd565b85516115e4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e1d565b6115ec6111d4565b86511115611626576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613dbd565b3360009081526005602052604090205480156116d757600061164782610ab3565b9050600181600781111561165757fe5b141561168f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e4d565b600081600781111561169d57fe5b14156116d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613d9d565b505b60006116e543610c55610aae565b905060006116f582610c5561054e565b600380546001019055905061170861247f565b604051806101a0016040528060035481526020013373ffffffffffffffffffffffffffffffffffffffff168152602001600081526020018b81526020018a815260200189815260200188815260200184815260200183815260200160008152602001600081526020016000151581526020016000151581525090508060046000836000015181526020019081526020016000206000820151816000015560208201518160010160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550604082015181600201556060820151816003019080519060200190611812929190612501565b506080820151805161182e91600484019160209091019061258b565b5060a0820151805161184a9160058401916020909101906125d2565b5060c0820151805161186691600684019160209091019061262b565b5060e082015181600701556101008201518160080155610120820151816009015561014082015181600a015561016082015181600b0160006101000a81548160ff02191690831515021790555061018082015181600b0160016101000a81548160ff021916908315150217905550905050806000015160056000836020015173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055507f7d84a6263ae0d98d3329bd7b46bb4e8d6f98cd35a7adb45c274c8b7fd5ebd5e08160000151338c8c8c8c89898e60405161196699989796959493929190613eab565b60405180910390a15193505050505b95945050505050565b600461198982610ab3565b600781111561199457fe5b146119cb576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613d4d565b6000818152600460208181526040808420845482517f6a42b8f80000000000000000000000000000000000000000000000000000000081529251919594611a4694429473ffffffffffffffffffffffffffffffffffffffff90931693636a42b8f8938084019390829003018186803b158015610c1d57600080fd5b905060005b6003830154811015611c3757611c2f836003018281548110611a6957fe5b60009182526020909120015460048501805473ffffffffffffffffffffffffffffffffffffffff9092169184908110611a9e57fe5b9060005260206000200154856005018481548110611ab857fe5b600091825260209182902001805460408051601f60027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff610100600187161502019094169390930492830185900485028101850190915281815292830182828015611b645780601f10611b3957610100808354040283529160200191611b64565b820191906000526020600020905b815481529060010190602001808311611b4757829003601f168201915b5050505050866006018581548110611b7857fe5b600091825260209182902001805460408051601f60027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff610100600187161502019094169390930492830185900485028101850190915281815292830182828015611c245780601f10611bf957610100808354040283529160200191611c24565b820191906000526020600020905b815481529060010190602001808311611c0757829003601f168201915b505050505086612282565b600101611a4b565b50600282018190556040517f9a2e42fd6722813d69113e7d0079d3d940171428df7373df9c7f7617cfda289290610f4e9085908490613fd9565b6040516105d790613acf565b611c85612684565b50600082815260046020908152604080832073ffffffffffffffffffffffffffffffffffffffff85168452600c018252918290208251606081018452815460ff808216151583526101009091041615159281019290925260010154918101919091525b92915050565b6005611cf982610ab3565b6007811115611d0457fe5b14611d3b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613d5d565b6000818152600460205260408120600b810180547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff16610100179055905b6003820154811015611ee65760005460048301805473ffffffffffffffffffffffffffffffffffffffff90921691630825f38f919084908110611db857fe5b9060005260206000200154846003018481548110611dd257fe5b60009182526020909120015460048601805473ffffffffffffffffffffffffffffffffffffffff9092169186908110611e0757fe5b9060005260206000200154866005018681548110611e2157fe5b90600052602060002001876006018781548110611e3a57fe5b9060005260206000200188600201546040518763ffffffff1660e01b8152600401611e69959493929190613bef565b6000604051808303818588803b158015611e8257600080fd5b505af1158015611e96573d6000803e3d6000fd5b50505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0168201604052611edd9190810190612bfc565b50600101611d79565b507f712ae1383f79ac853f8d882153778e0260ef8f03b504e2866e0593e04d2b291f82604051611f169190613c7d565b60405180910390a15050565b6001611f2d83610ab3565b6007811115611f3857fe5b14611f6f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e6d565b600082815260046020908152604080832073ffffffffffffffffffffffffffffffffffffffff87168452600c8101909252909120805460ff1615611fdf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613d8d565b60015460078301546040517f782d6fe100000000000000000000000000000000000000000000000000000000815260009273ffffffffffffffffffffffffffffffffffffffff169163782d6fe19161203b918a91600401613b52565b60206040518083038186803b15801561205357600080fd5b505afa158015612067573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061208b9190810190612bde565b905083156120ab576120a18360090154826121fd565b60098401556120bf565b6120b983600a0154826121fd565b600a8401555b815460017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0090911681177fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff166101008615150217835582018190556040517f877856338e13f63d0c36822ff0ef736b80934cd90574a3a5bc9262c39d217c4690612150908890889088908690613b60565b60405180910390a1505050505050565b60008261216f57506000611ce8565b8282028284828161217c57fe5b04146121b4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613ded565b9392505050565b60006121b483836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061242e565b6000828201838110156121b4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613dcd565b600082821115612278576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e7d565b50900390565b4690565b60005460405173ffffffffffffffffffffffffffffffffffffffff9091169063f2b06537906122bd9088908890889088908890602001613b95565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016122ef9190613c7d565b60206040518083038186803b15801561230757600080fd5b505afa15801561231b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061233f9190810190612bc0565b15612376576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161063390613e0d565b6000546040517f3a66f90100000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff90911690633a66f901906123d49088908890889088908890600401613b95565b602060405180830381600087803b1580156123ee57600080fd5b505af1158015612402573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506124269190810190612bde565b505050505050565b60008183612469576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016106339190613d2c565b50600083858161247557fe5b0495945050505050565b604051806101a0016040528060008152602001600073ffffffffffffffffffffffffffffffffffffffff1681526020016000815260200160608152602001606081526020016060815260200160608152602001600081526020016000815260200160008152602001600081526020016000151581526020016000151581525090565b82805482825590600052602060002090810192821561257b579160200282015b8281111561257b57825182547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff909116178255602090920191600190910190612521565b506125879291506126a4565b5090565b8280548282559060005260206000209081019282156125c6579160200282015b828111156125c65782518255916020019190600101906125ab565b506125879291506126e0565b82805482825590600052602060002090810192821561261f579160200282015b8281111561261f578251805161260f9184916020909101906126fa565b50916020019190600101906125f2565b50612587929150612767565b828054828255906000526020600020908101928215612678579160200282015b8281111561267857825180516126689184916020909101906126fa565b509160200191906001019061264b565b5061258792915061278a565b604080516060810182526000808252602082018190529181019190915290565b61055291905b808211156125875780547fffffffffffffffffffffffff00000000000000000000000000000000000000001681556001016126aa565b61055291905b8082111561258757600081556001016126e6565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061273b57805160ff19168380011785556125c6565b828001600101855582156125c657918201828111156125c65782518255916020019190600101906125ab565b61055291905b8082111561258757600061278182826127ad565b5060010161276d565b61055291905b808211156125875760006127a482826127ad565b50600101612790565b50805460018160011615610100020316600290046000825580601f106127d357506127f1565b601f0160209004906000526020600020908101906127f191906126e0565b50565b8035611ce88161415f565b600082601f83011261281057600080fd5b813561282361281e8261400e565b613fe7565b9150818183526020840193506020810190508385602084028201111561284857600080fd5b60005b83811015612874578161285e88826127f4565b845250602092830192919091019060010161284b565b5050505092915050565b600082601f83011261288f57600080fd5b813561289d61281e8261400e565b81815260209384019390925082018360005b8381101561287457813586016128c588826129d4565b84525060209283019291909101906001016128af565b600082601f8301126128ec57600080fd5b81356128fa61281e8261400e565b81815260209384019390925082018360005b83811015612874578135860161292288826129d4565b845250602092830192919091019060010161290c565b600082601f83011261294957600080fd5b813561295761281e8261400e565b9150818183526020840193506020810190508385602084028201111561297c57600080fd5b60005b83811015612874578161299288826129be565b845250602092830192919091019060010161297f565b8035611ce881614173565b8051611ce881614173565b8035611ce88161417c565b8051611ce88161417c565b600082601f8301126129e557600080fd5b81356129f361281e8261402f565b91508082526020830160208301858383011115612a0f57600080fd5b612a1a8382846140f5565b50505092915050565b600082601f830112612a3457600080fd5b8151612a4261281e8261402f565b91508082526020830160208301858383011115612a5e57600080fd5b612a1a838284614101565b8035611ce881614185565b600060208284031215612a8657600080fd5b6000612a9284846127f4565b949350505050565b60008060408385031215612aad57600080fd5b6000612ab985856127f4565b9250506020612aca858286016129be565b9150509250929050565b600080600080600060a08688031215612aec57600080fd5b853567ffffffffffffffff811115612b0357600080fd5b612b0f888289016127ff565b955050602086013567ffffffffffffffff811115612b2c57600080fd5b612b3888828901612938565b945050604086013567ffffffffffffffff811115612b5557600080fd5b612b61888289016128db565b935050606086013567ffffffffffffffff811115612b7e57600080fd5b612b8a8882890161287e565b925050608086013567ffffffffffffffff811115612ba757600080fd5b612bb3888289016129d4565b9150509295509295909350565b600060208284031215612bd257600080fd5b6000612a9284846129b3565b600060208284031215612bf057600080fd5b6000612a9284846129c9565b600060208284031215612c0e57600080fd5b815167ffffffffffffffff811115612c2557600080fd5b612a9284828501612a23565b600060208284031215612c4357600080fd5b6000612a9284846129be565b60008060408385031215612c6257600080fd5b6000612c6e85856129be565b9250506020612aca858286016127f4565b60008060408385031215612c9257600080fd5b6000612c9e85856129be565b9250506020612aca858286016129a8565b600080600080600060a08688031215612cc757600080fd5b6000612cd388886129be565b9550506020612ce4888289016129a8565b9450506040612cf588828901612a69565b9350506060612d06888289016129be565b9250506080612bb3888289016129be565b6000612d238383612d52565b505060200190565b60006121b48383612ef4565b6000612d238383612eda565b612d4c816140cd565b82525050565b612d4c81614094565b6000612d6682614087565b612d70818561408b565b9350612d7b83614075565b8060005b83811015612da9578151612d938882612d17565b9750612d9e83614075565b925050600101612d7f565b509495945050505050565b6000612dbf82614087565b612dc9818561408b565b935083602082028501612ddb85614075565b8060005b85811015612e155784840389528151612df88582612d2b565b9450612e0383614075565b60209a909a0199925050600101612ddf565b5091979650505050505050565b6000612e2d82614087565b612e37818561408b565b935083602082028501612e4985614075565b8060005b85811015612e155784840389528151612e668582612d2b565b9450612e7183614075565b60209a909a0199925050600101612e4d565b6000612e8e82614087565b612e98818561408b565b9350612ea383614075565b8060005b83811015612da9578151612ebb8882612d37565b9750612ec683614075565b925050600101612ea7565b612d4c8161409f565b612d4c81610552565b612d4c612eef82610552565b610552565b6000612eff82614087565b612f09818561408b565b9350612f19818560208601614101565b612f228161412d565b9093019392505050565b600081546001811660008114612f495760018114612f8d57612fcc565b607f6002830416612f5a818761408b565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0084168152955050602085019250612fcc565b60028204612f9b818761408b565b9550612fa68561407b565b60005b82811015612fc557815488820152600190910190602001612fa9565b8701945050505b505092915050565b612d4c816140d4565b612d4c816140df565b612d4c816140ea565b6000612ffc60398361408b565b7f476f7665726e6f72416c7068613a3a5f5f61636365707441646d696e3a20736581527f6e646572206d75737420626520676f7620677561726469616e00000000000000602082015260400192915050565b600061305b60448361408b565b7f476f7665726e6f72416c7068613a3a71756575653a2070726f706f73616c206381527f616e206f6e6c792062652071756575656420696620697420697320737563636560208201527f6564656400000000000000000000000000000000000000000000000000000000604082015260600192915050565b60006130e060458361408b565b7f476f7665726e6f72416c7068613a3a657865637574653a2070726f706f73616c81527f2063616e206f6e6c79206265206578656375746564206966206974206973207160208201527f7565756564000000000000000000000000000000000000000000000000000000604082015260600192915050565b6000613165600283610c70565b7f1901000000000000000000000000000000000000000000000000000000000000815260020192915050565b600061319e604c8361408b565b7f476f7665726e6f72416c7068613a3a5f5f6578656375746553657454696d656c81527f6f636b50656e64696e6741646d696e3a2073656e646572206d7573742062652060208201527f676f7620677561726469616e0000000000000000000000000000000000000000604082015260600192915050565b600061322360188361408b565b7f73657450656e64696e6741646d696e2861646472657373290000000000000000815260200192915050565b600061325c60298361408b565b7f476f7665726e6f72416c7068613a3a73746174653a20696e76616c696420707281527f6f706f73616c2069640000000000000000000000000000000000000000000000602082015260400192915050565b60006132bb602d8361408b565b7f476f7665726e6f72416c7068613a3a5f63617374566f74653a20766f7465722081527f616c726561647920766f74656400000000000000000000000000000000000000602082015260400192915050565b600061331a60598361408b565b7f476f7665726e6f72416c7068613a3a70726f706f73653a206f6e65206c69766581527f2070726f706f73616c207065722070726f706f7365722c20666f756e6420616e60208201527f20616c72656164792070656e64696e672070726f706f73616c00000000000000604082015260600192915050565b600061339f604a8361408b565b7f476f7665726e6f72416c7068613a3a5f5f717565756553657454696d656c6f6381527f6b50656e64696e6741646d696e3a2073656e646572206d75737420626520676f60208201527f7620677561726469616e00000000000000000000000000000000000000000000604082015260600192915050565b600061342460288361408b565b7f476f7665726e6f72416c7068613a3a70726f706f73653a20746f6f206d616e7981527f20616374696f6e73000000000000000000000000000000000000000000000000602082015260400192915050565b600061348360118361408b565b7f6164646974696f6e206f766572666c6f77000000000000000000000000000000815260200192915050565b60006134bc604383610c70565b7f454950373132446f6d61696e28737472696e67206e616d652c75696e7432353681527f20636861696e49642c6164647265737320766572696679696e67436f6e74726160208201527f6374290000000000000000000000000000000000000000000000000000000000604082015260430192915050565b6000613541602783610c70565b7f42616c6c6f742875696e743235362070726f706f73616c49642c626f6f6c207381527f7570706f72742900000000000000000000000000000000000000000000000000602082015260270192915050565b60006135a060448361408b565b7f476f7665726e6f72416c7068613a3a70726f706f73653a2070726f706f73616c81527f2066756e6374696f6e20696e666f726d6174696f6e206172697479206d69736d60208201527f6174636800000000000000000000000000000000000000000000000000000000604082015260600192915050565b600061362560218361408b565b7f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f81527f7700000000000000000000000000000000000000000000000000000000000000602082015260400192915050565b6000613684602f8361408b565b7f476f7665726e6f72416c7068613a3a63616e63656c3a2070726f706f7365722081527f61626f7665207468726573686f6c640000000000000000000000000000000000602082015260400192915050565b60006136e360448361408b565b7f476f7665726e6f72416c7068613a3a5f71756575654f725265766572743a207081527f726f706f73616c20616374696f6e20616c72656164792071756575656420617460208201527f2065746100000000000000000000000000000000000000000000000000000000604082015260600192915050565b6000613768602c8361408b565b7f476f7665726e6f72416c7068613a3a70726f706f73653a206d7573742070726f81527f7669646520616374696f6e730000000000000000000000000000000000000000602082015260400192915050565b60006137c7603f8361408b565b7f476f7665726e6f72416c7068613a3a70726f706f73653a2070726f706f73657281527f20766f7465732062656c6f772070726f706f73616c207468726573686f6c6400602082015260400192915050565b6000613826602f8361408b565b7f476f7665726e6f72416c7068613a3a63617374566f746542795369673a20696e81527f76616c6964207369676e61747572650000000000000000000000000000000000602082015260400192915050565b600061388560588361408b565b7f476f7665726e6f72416c7068613a3a70726f706f73653a206f6e65206c69766581527f2070726f706f73616c207065722070726f706f7365722c20666f756e6420616e60208201527f20616c7265616479206163746976652070726f706f73616c0000000000000000604082015260600192915050565b600061390a60368361408b565b7f476f7665726e6f72416c7068613a3a63616e63656c3a2063616e6e6f7420636181527f6e63656c2065786563757465642070726f706f73616c00000000000000000000602082015260400192915050565b6000613969602a8361408b565b7f476f7665726e6f72416c7068613a3a5f63617374566f74653a20766f74696e6781527f20697320636c6f73656400000000000000000000000000000000000000000000602082015260400192915050565b60006139c860158361408b565b7f7375627472616374696f6e20756e646572666c6f770000000000000000000000815260200192915050565b6000613a0160368361408b565b7f476f7665726e6f72416c7068613a3a5f5f61626469636174653a2073656e646581527f72206d75737420626520676f7620677561726469616e00000000000000000000602082015260400192915050565b80516060830190613a648482612ed1565b506020820151613a776020850182612ed1565b5060408201516114536040850182612eda565b612d4c816140c7565b6000613a9e82613158565b9150613aaa8285612ee3565b602082019150613aba8284612ee3565b5060200192915050565b6000611ce8826134af565b6000611ce882613534565b60208101611ce88284612d52565b60408101613af68285612d43565b6121b46020830184612eda565b60a08101613b118287612d52565b613b1e6020830186612fe6565b8181036040830152613b2f81613216565b90508181036060830152613b438185612ef4565b90506119756080830184612eda565b60408101613af68285612d52565b60808101613b6e8287612d52565b613b7b6020830186612eda565b613b886040830185612ed1565b6119756060830184612eda565b60a08101613ba38288612d52565b613bb06020830187612eda565b8181036040830152613bc28186612ef4565b90508181036060830152613bd68185612ef4565b9050613be56080830184612eda565b9695505050505050565b60a08101613bfd8288612d52565b613c0a6020830187612eda565b8181036040830152613c1c8186612f2c565b90508181036060830152613bd68185612f2c565b60808082528101613c418187612d5b565b90508181036020830152613c558186612e83565b90508181036040830152613c698185612e22565b90508181036060830152613be58184612db4565b60208101611ce88284612eda565b60808101613c998287612eda565b613ca66020830186612eda565b613cb36040830185612eda565b6119756060830184612d52565b60608101613cce8286612eda565b613cdb6020830185612eda565b612a926040830184612ed1565b60808101613cf68287612eda565b613d036020830186613a8a565b613b886040830185612eda565b60208101611ce88284612fd4565b60208101611ce88284612fdd565b602080825281016121b48184612ef4565b60208082528101611ce881612fef565b60208082528101611ce88161304e565b60208082528101611ce8816130d3565b60208082528101611ce881613191565b60208082528101611ce88161324f565b60208082528101611ce8816132ae565b60208082528101611ce88161330d565b60208082528101611ce881613392565b60208082528101611ce881613417565b60208082528101611ce881613476565b60208082528101611ce881613593565b60208082528101611ce881613618565b60208082528101611ce881613677565b60208082528101611ce8816136d6565b60208082528101611ce88161375b565b60208082528101611ce8816137ba565b60208082528101611ce881613819565b60208082528101611ce881613878565b60208082528101611ce8816138fd565b60208082528101611ce88161395c565b60208082528101611ce8816139bb565b60208082528101611ce8816139f4565b60608101611ce88284613a53565b6101208101613eba828c612eda565b613ec7602083018b612d43565b8181036040830152613ed9818a612d5b565b90508181036060830152613eed8189612e83565b90508181036080830152613f018188612e22565b905081810360a0830152613f158187612db4565b9050613f2460c0830186612eda565b613f3160e0830185612eda565b818103610100830152613f448184612ef4565b9b9a5050505050505050505050565b6101208101613f62828c612eda565b613f6f602083018b612d52565b613f7c604083018a612eda565b613f896060830189612eda565b613f966080830188612eda565b613fa360a0830187612eda565b613fb060c0830186612eda565b613fbd60e0830185612ed1565b613fcb610100830184612ed1565b9a9950505050505050505050565b60408101613af68285612eda565b60405181810167ffffffffffffffff8111828210171561400657600080fd5b604052919050565b600067ffffffffffffffff82111561402557600080fd5b5060209081020190565b600067ffffffffffffffff82111561404657600080fd5b506020601f919091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0160190565b60200190565b60009081526020902090565b5190565b90815260200190565b6000611ce8826140ae565b151590565b80610c7081614155565b73ffffffffffffffffffffffffffffffffffffffff1690565b60ff1690565b6000611ce8825b6000611ce882614094565b6000611ce8826140a4565b6000611ce882610552565b82818337506000910152565b60005b8381101561411c578181015183820152602001614104565b838111156114535750506000910152565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690565b600881106127f157fe5b61416881614094565b81146127f157600080fd5b6141688161409f565b61416881610552565b614168816140c756fea365627a7a72315820912bca945f7259d993e0a2ed5501f11583c82f4c662281d9de1b35f7d96c54256c6578706572696d656e74616cf564736f6c63430005110040
[ 4, 7, 11, 16, 9, 12, 10, 5 ]
0x4B3fBe6d554c540C2672eB7A501018a1A39f7F53
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ERC20 { function totalSupply() external view returns (uint); function decimals() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); } interface IFeature { enum OwnerSignature { Anyone, // Anyone Required, // Owner required Optional, // Owner and/or guardians Disallowed // guardians only } /** * @notice Utility method to recover any ERC20 token that was sent to the Feature by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; /** * @notice Inits a Feature for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(address _wallet) external; /** * @notice Helper method to check if an address is an authorised feature of a target wallet. * @param _wallet The target wallet. * @param _feature The address. */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) external view returns (bool); /** * @notice Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures and the wallet owner signature requirement. */ function getRequiredSignatures(address _wallet, bytes calldata _data) external view returns (uint256, OwnerSignature); /** * @notice Gets the list of static call signatures that this feature responds to on behalf of wallets */ function getStaticCallSignatures() external view returns (bytes4[] memory); } interface IGuardianStorage { /** * @notice Lets an authorised module add a guardian to a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(address _wallet, address _guardian) external; /** * @notice Lets an authorised module revoke a guardian from a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(address _wallet, address _guardian) external; /** * @notice Checks if an account is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The account. * @return true if the account is a guardian for a wallet. */ function isGuardian(address _wallet, address _guardian) external view returns (bool); function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, uint256 _releaseAfter) external; function getGuardians(address _wallet) external view returns (address[] memory); function guardianCount(address _wallet) external view returns (uint256); } interface ILimitStorage { struct Limit { // the current limit uint128 current; // the pending limit if any uint128 pending; // when the pending limit becomes the current limit uint64 changeAfter; } struct DailySpent { // The amount already spent during the current period uint128 alreadySpent; // The end of the current period uint64 periodEnd; } function setLimit(address _wallet, Limit memory _limit) external; function getLimit(address _wallet) external view returns (Limit memory _limit); function setDailySpent(address _wallet, DailySpent memory _dailySpent) external; function getDailySpent(address _wallet) external view returns (DailySpent memory _dailySpent); function setLimitAndDailySpent(address _wallet, Limit memory _limit, DailySpent memory _dailySpent) external; function getLimitAndDailySpent(address _wallet) external view returns (Limit memory _limit, DailySpent memory _dailySpent); } interface ILockStorage { function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, address _locker, uint256 _releaseAfter) external; } interface IModule { /** * @notice Inits a module for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(address _wallet) external; /** * @notice Adds a module to a wallet. Cannot execute when wallet is locked (or under recovery) * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(address _wallet, address _module) external; } interface IModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } interface ITransferStorage { function setWhitelist(address _wallet, address _target, uint256 _value) external; function getWhitelist(address _wallet, address _target) external view returns (uint256); } interface IVersionManager { /** * @notice Returns true if the feature is authorised for the wallet * @param _wallet The target wallet. * @param _feature The feature. */ function isFeatureAuthorised(address _wallet, address _feature) external view returns (bool); /** * @notice Lets a feature (caller) invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function checkAuthorisedFeatureAndInvokeWallet( address _wallet, address _to, uint256 _value, bytes calldata _data ) external returns (bytes memory _res); /* ******* Backward Compatibility with old Storages and BaseWallet *************** */ /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _wallet, address _newOwner) external; /** * @notice Lets a feature write data to a storage contract. * @param _wallet The target wallet. * @param _storage The storage contract. * @param _data The data of the call */ function invokeStorage(address _wallet, address _storage, bytes calldata _data) external; /** * @notice Upgrade a wallet to a new version. * @param _wallet the wallet to upgrade * @param _toVersion the new version */ function upgradeWallet(address _wallet, uint256 _toVersion) external; } interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; } contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @notice Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @notice Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Address must not be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Utils { /** * @notice Helper method to recover the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); address recoveredAddress = ecrecover(_signedHash, v, r, s); require(recoveredAddress != address(0), "Utils: ecrecover returned 0"); return recoveredAddress; } /** * @notice Helper method to parse data and extract the method signature. */ function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solhint-disable-next-line no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } /** * @notice Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; if (a % b == 0) { return c; } else { return c + 1; } } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } return b; } } contract BaseFeature is IFeature { // Empty calldata bytes constant internal EMPTY_BYTES = ""; // Mock token address for ETH address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // The address of the Lock storage ILockStorage internal lockStorage; // The address of the Version Manager IVersionManager internal versionManager; event FeatureCreated(bytes32 name); /** * @notice Throws if the wallet is locked. */ modifier onlyWhenUnlocked(address _wallet) { require(!lockStorage.isLocked(_wallet), "BF: wallet locked"); _; } /** * @notice Throws if the sender is not the VersionManager. */ modifier onlyVersionManager() { require(msg.sender == address(versionManager), "BF: caller must be VersionManager"); _; } /** * @notice Throws if the sender is not the owner of the target wallet. */ modifier onlyWalletOwner(address _wallet) { require(isOwner(_wallet, msg.sender), "BF: must be wallet owner"); _; } /** * @notice Throws if the sender is not an authorised feature of the target wallet. */ modifier onlyWalletFeature(address _wallet) { require(versionManager.isFeatureAuthorised(_wallet, msg.sender), "BF: must be a wallet feature"); _; } /** * @notice Throws if the sender is not the owner of the target wallet or the feature itself. */ modifier onlyWalletOwnerOrFeature(address _wallet) { // Wrapping in an internal method reduces deployment cost by avoiding duplication of inlined code verifyOwnerOrAuthorisedFeature(_wallet, msg.sender); _; } constructor( ILockStorage _lockStorage, IVersionManager _versionManager, bytes32 _name ) public { lockStorage = _lockStorage; versionManager = _versionManager; emit FeatureCreated(_name); } /** * @inheritdoc IFeature */ function recoverToken(address _token) external virtual override { uint total = ERC20(_token).balanceOf(address(this)); _token.call(abi.encodeWithSelector(ERC20(_token).transfer.selector, address(versionManager), total)); } /** * @notice Inits the feature for a wallet by doing nothing. * @dev !! Overriding methods need make sure `init()` can only be called by the VersionManager !! * @param _wallet The wallet. */ function init(address _wallet) external virtual override {} /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external virtual view override returns (uint256, OwnerSignature) { revert("BF: disabled method"); } /** * @inheritdoc IFeature */ function getStaticCallSignatures() external virtual override view returns (bytes4[] memory _sigs) {} /** * @inheritdoc IFeature */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) public override view returns (bool) { return versionManager.isFeatureAuthorised(_wallet, _feature); } /** * @notice Checks that the wallet address provided as the first parameter of _data matches _wallet * @return false if the addresses are different. */ function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet = abi.decode(_data[4:], (address)); return dataWallet == _wallet; } /** * @notice Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(address _wallet, address _addr) internal view returns (bool) { return IWallet(_wallet).owner() == _addr; } /** * @notice Verify that the caller is an authorised feature or the wallet owner. * @param _wallet The target wallet. * @param _sender The caller. */ function verifyOwnerOrAuthorisedFeature(address _wallet, address _sender) internal view { require(isFeatureAuthorisedInVersionManager(_wallet, _sender) || isOwner(_wallet, _sender), "BF: must be owner or feature"); } /** * @notice Helper method to invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) { _res = versionManager.checkAuthorisedFeatureAndInvokeWallet(_wallet, _to, _value, _data); } } contract VersionManager is IVersionManager, IModule, BaseFeature, Owned { bytes32 constant NAME = "VersionManager"; bytes4 constant internal ADD_MODULE_PREFIX = bytes4(keccak256("addModule(address,address)")); bytes4 constant internal UPGRADE_WALLET_PREFIX = bytes4(keccak256("upgradeWallet(address,uint256)")); // Last bundle version uint256 public lastVersion; // Minimum allowed version uint256 public minVersion = 1; // Current bundle version for a wallet mapping(address => uint256) public walletVersions; // [wallet] => [version] // Features per version mapping(address => mapping(uint256 => bool)) public isFeatureInVersion; // [feature][version] => bool // Features requiring initialization for a wallet mapping(uint256 => address[]) public featuresToInit; // [version] => [features] // Supported static call signatures mapping(uint256 => bytes4[]) public staticCallSignatures; // [version] => [sigs] // Features executing static calls mapping(uint256 => mapping(bytes4 => address)) public staticCallExecutors; // [version][sig] => [feature] // Authorised Storages mapping(address => bool) public isStorage; // [storage] => bool event VersionAdded(uint256 _version, address[] _features); event WalletUpgraded(address indexed _wallet, uint256 _version); // The Module Registry IModuleRegistry private registry; /* ***************** Constructor ************************* */ constructor( IModuleRegistry _registry, ILockStorage _lockStorage, IGuardianStorage _guardianStorage, ITransferStorage _transferStorage, ILimitStorage _limitStorage ) BaseFeature(_lockStorage, IVersionManager(address(this)), NAME) public { registry = _registry; // Add initial storages if(address(_lockStorage) != address(0)) { addStorage(address(_lockStorage)); } if(address(_guardianStorage) != address(0)) { addStorage(address(_guardianStorage)); } if(address(_transferStorage) != address(0)) { addStorage(address(_transferStorage)); } if(address(_limitStorage) != address(0)) { addStorage(address(_limitStorage)); } } /* ***************** onlyOwner ************************* */ /** * @inheritdoc IFeature */ function recoverToken(address _token) external override onlyOwner { uint total = ERC20(_token).balanceOf(address(this)); _token.call(abi.encodeWithSelector(ERC20(_token).transfer.selector, msg.sender, total)); } /** * @notice Lets the owner change the minimum allowed version * @param _minVersion the minimum allowed version */ function setMinVersion(uint256 _minVersion) external onlyOwner { require(_minVersion > 0 && _minVersion <= lastVersion, "VM: invalid _minVersion"); minVersion = _minVersion; } /** * @notice Lets the owner add a new version, i.e. a new bundle of features. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * WARNING: if a feature was added to a version and later on removed from a subsequent version, * the feature may no longer be used in any future version without first being redeployed. * Otherwise, the feature could be initialized more than once. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * @param _features the list of features included in the new version * @param _featuresToInit the subset of features that need to be initialized for a wallet */ function addVersion(address[] calldata _features, address[] calldata _featuresToInit) external onlyOwner { uint256 newVersion = ++lastVersion; for(uint256 i = 0; i < _features.length; i++) { isFeatureInVersion[_features[i]][newVersion] = true; // Store static call information to optimise its use by wallets bytes4[] memory sigs = IFeature(_features[i]).getStaticCallSignatures(); for(uint256 j = 0; j < sigs.length; j++) { staticCallSignatures[newVersion].push(sigs[j]); staticCallExecutors[newVersion][sigs[j]] = _features[i]; } } // Sanity check for(uint256 i = 0; i < _featuresToInit.length; i++) { require(isFeatureInVersion[_featuresToInit[i]][newVersion], "VM: invalid _featuresToInit"); } featuresToInit[newVersion] = _featuresToInit; emit VersionAdded(newVersion, _features); } /** * @notice Lets the owner add a storage contract * @param _storage the storage contract to add */ function addStorage(address _storage) public onlyOwner { require(!isStorage[_storage], "VM: storage already added"); isStorage[_storage] = true; } /* ***************** View Methods ************************* */ /** * @inheritdoc IVersionManager */ function isFeatureAuthorised(address _wallet, address _feature) external view override returns (bool) { // Note that the VersionManager is the only feature that isn't stored in isFeatureInVersion return _isFeatureAuthorisedForWallet(_wallet, _feature) || _feature == address(this); } /** * @inheritdoc IFeature */ function getRequiredSignatures(address /* _wallet */, bytes calldata _data) external view override returns (uint256, OwnerSignature) { bytes4 methodId = Utils.functionPrefix(_data); // This require ensures that the RelayerManager cannot be used to call a featureOnly VersionManager method // that calls a Storage or the BaseWallet for backward-compatibility reason require(methodId == UPGRADE_WALLET_PREFIX || methodId == ADD_MODULE_PREFIX, "VM: unknown method"); return (1, OwnerSignature.Required); } /** * @notice This method delegates the static call to a target feature */ fallback() external { uint256 version = walletVersions[msg.sender]; address feature = staticCallExecutors[version][msg.sig]; require(feature != address(0), "VM: static call not supported for wallet version"); // solhint-disable-next-line no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas(), feature, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } /* ***************** Wallet Upgrade ************************* */ /** * @inheritdoc IFeature */ function init(address _wallet) public override(IModule, BaseFeature) {} /** * @inheritdoc IVersionManager */ function upgradeWallet(address _wallet, uint256 _toVersion) external override onlyWhenUnlocked(_wallet) { require( // Upgrade triggered by the RelayerManager (from version v>=1 to version v'>v) _isFeatureAuthorisedForWallet(_wallet, msg.sender) || // Upgrade triggered by WalletFactory or UpgraderToVersionManager (from version v=0 to version v'>0) IWallet(_wallet).authorised(msg.sender) || // Upgrade triggered directly by the owner (from version v>=1 to version v'>v) isOwner(_wallet, msg.sender), "VM: sender may not upgrade wallet" ); uint256 fromVersion = walletVersions[_wallet]; uint256 minVersion_ = minVersion; uint256 toVersion; if(_toVersion < minVersion_ && fromVersion == 0 && IWallet(_wallet).modules() == 2) { // When the caller is the WalletFactory, we automatically change toVersion to minVersion if needed. // Note that when fromVersion == 0, the caller could be the WalletFactory or the UpgraderToVersionManager. // The WalletFactory will be the only possible caller when the wallet has only 2 authorised modules // (that number would be >= 3 for a call from the UpgraderToVersionManager) toVersion = minVersion_; } else { toVersion = _toVersion; } require(toVersion >= minVersion_ && toVersion <= lastVersion, "VM: invalid _toVersion"); require(fromVersion < toVersion, "VM: already on new version"); walletVersions[_wallet] = toVersion; // Setup static call redirection bytes4[] storage sigs = staticCallSignatures[toVersion]; for(uint256 i = 0; i < sigs.length; i++) { bytes4 sig = sigs[i]; if(IWallet(_wallet).enabled(sig) != address(this)) { IWallet(_wallet).enableStaticCall(address(this), sig); } } // Init features address[] storage featuresToInitInToVersion = featuresToInit[toVersion]; for(uint256 i = 0; i < featuresToInitInToVersion.length; i++) { address feature = featuresToInitInToVersion[i]; // We only initialize a feature that was not already initialized in the previous version if(fromVersion == 0 || !isFeatureInVersion[feature][fromVersion]) { IFeature(feature).init(_wallet); } } emit WalletUpgraded(_wallet, toVersion); } /** * @inheritdoc IModule */ function addModule(address _wallet, address _module) external override onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { require(registry.isRegisteredModule(_module), "VM: module is not registered"); IWallet(_wallet).authoriseModule(_module, true); } /* ******* Backward Compatibility with old Storages and BaseWallet *************** */ /** * @inheritdoc IVersionManager */ function checkAuthorisedFeatureAndInvokeWallet( address _wallet, address _to, uint256 _value, bytes memory _data ) external override returns (bytes memory _res) { require(_isFeatureAuthorisedForWallet(_wallet, msg.sender), "VM: sender may not invoke wallet"); bool success; (success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data)); if (success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values (_res) = abi.decode(_res, (bytes)); } else if (_res.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } else if (!success) { revert("VM: wallet invoke reverted"); } } /** * @inheritdoc IVersionManager */ function invokeStorage(address _wallet, address _storage, bytes calldata _data) external override { require(_isFeatureAuthorisedForWallet(_wallet, msg.sender), "VM: sender may not invoke storage"); require(verifyData(_wallet, _data), "VM: target of _data != _wallet"); require(isStorage[_storage], "VM: invalid storage invoked"); (bool success,) = _storage.call(_data); require(success, "VM: _storage failed"); } /** * @inheritdoc IVersionManager */ function setOwner(address _wallet, address _newOwner) external override { require(_isFeatureAuthorisedForWallet(_wallet, msg.sender), "VM: sender should be authorized feature"); IWallet(_wallet).setOwner(_newOwner); } /* ***************** Internal Methods ************************* */ function _isFeatureAuthorisedForWallet(address _wallet, address _feature) private view returns (bool) { return isFeatureInVersion[_feature][walletVersions[_wallet]]; } }
0x608060405234801561001057600080fd5b50600436106101985760003560e01c80638da5cb5b116100e3578063e3495a391161008c578063ea2347e611610066578063ea2347e6146103e5578063eb40f32b146103fa578063ef1243a41461040d57610198565b8063e3495a39146103b7578063e452b790146103ca578063e6516a15146103dd57610198565b8063a287fdbd116100bd578063a287fdbd14610371578063a6cc33c614610384578063a6f9dae1146103a457610198565b80638da5cb5b14610329578063915c77b91461033e5780639be65a601461035e57610198565b80633b73d67f1161014557806364dfea061161011f57806364dfea06146102ee57806367d82ac3146103035780636d7163341461031657610198565b80633b73d67f146102a75780635a1db8c4146102c85780635a51fd43146102db57610198565b806319ab453c1161017657806319ab453c1461026e57806324ee628214610281578063299a7bcc1461029457610198565b806309abb4f41461021d578063162d58a514610232578063165783891461025b575b33600090815260056020908152604080832054808452600983528184206001600160e01b03198535168552909252909120546001600160a01b0316806101f95760405162461bcd60e51b81526004016101f090612334565b60405180910390fd5b3660008037600080366000845afa3d6000803e808015610218573d6000f35b3d6000fd5b61023061022b3660046119c1565b610420565b005b6102456102403660046119c1565b6104a7565b6040516102529190611f10565b60405180910390f35b610230610269366004611bc0565b6104bc565b61023061027c3660046119c1565b6107e2565b61024561028f366004611b95565b6107e5565b6102306102a2366004611a00565b610805565b6102ba6102b5366004611b42565b6108a6565b6040516102529291906124e8565b6102306102d6366004611a00565b610977565b6102456102e9366004611a00565b610b54565b6102f6610b7c565b6040516102529190612493565b610230610311366004611d48565b610b82565b6102f66103243660046119c1565b610bdf565b610331610bf1565b6040516102529190611e15565b61035161034c366004611a9b565b610c00565b6040516102529190611f30565b61023061036c3660046119c1565b610d58565b61024561037f366004611a00565b610edd565b610397610392366004611d9c565b610f79565b6040516102529190611f1b565b6102306103b23660046119c1565b610fbc565b6102306103c5366004611b95565b611063565b6102306103d8366004611a38565b6115a2565b6102f66116a6565b6103ed6116ac565b6040516102529190611ec2565b610331610408366004611d9c565b6116b1565b61033161041b366004611d78565b6116e6565b6002546001600160a01b0316331461044a5760405162461bcd60e51b81526004016101f0906121c4565b6001600160a01b0381166000908152600a602052604090205460ff16156104835760405162461bcd60e51b81526004016101f090612269565b6001600160a01b03166000908152600a60205260409020805460ff19166001179055565b600a6020526000908152604090205460ff1681565b6002546001600160a01b031633146104e65760405162461bcd60e51b81526004016101f0906121c4565b600380546001019081905560005b848110156107065760016006600088888581811061050e57fe5b905060200201602081019061052391906119c1565b6001600160a01b03168152602080820192909252604090810160009081208682529092529020805460ff1916911515919091179055606086868381811061056657fe5b905060200201602081019061057b91906119c1565b6001600160a01b031663ea2347e66040518163ffffffff1660e01b815260040160006040518083038186803b1580156105b357600080fd5b505afa1580156105c7573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526105ef9190810190611c1d565b905060005b81518110156106fc576000848152600860205260409020825183908390811061061957fe5b60209081029190910181015182546001810184556000938452919092206008820401805463ffffffff60079093166004026101000a928302191660e09390931c9190910291909117905587878481811061066f57fe5b905060200201602081019061068491906119c1565b6009600086815260200190815260200160002060008484815181106106a557fe5b6020908102919091018101516001600160e01b0319168252810191909152604001600020805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b03929092169190911790556001016105f4565b50506001016104f4565b5060005b82811015610785576006600085858481811061072257fe5b905060200201602081019061073791906119c1565b6001600160a01b031681526020808201929092526040908101600090812085825290925290205460ff1661077d5760405162461bcd60e51b81526004016101f090612391565b60010161070a565b50600081815260076020526040902061079f908484611891565b507f57012e25cd9d1b245def3547b1bff6d3bb7e5e33194d7b85b3ceebdb940e96aa8186866040516107d39392919061249c565b60405180910390a15050505050565b50565b600660209081526000928352604080842090915290825290205460ff1681565b61080f823361170c565b61082b5760405162461bcd60e51b81526004016101f0906122a0565b6040517f13af40350000000000000000000000000000000000000000000000000000000081526001600160a01b038316906313af403590610870908490600401611e15565b600060405180830381600087803b15801561088a57600080fd5b505af115801561089e573d6000803e3d6000fd5b505050505050565b60008060006108ea85858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061174592505050565b90506001600160e01b031981167fe3495a3900000000000000000000000000000000000000000000000000000000148061094d57506001600160e01b031981167f5a1db8c400000000000000000000000000000000000000000000000000000000145b6109695760405162461bcd60e51b81526004016101f090611f43565b506001958695509350505050565b816109828133611771565b600054604051631293efbb60e21b815284916001600160a01b031690634a4fbeec906109b2908490600401611e15565b60206040518083038186803b1580156109ca57600080fd5b505afa1580156109de573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a029190611cb5565b15610a1f5760405162461bcd60e51b81526004016101f0906120b1565b600b546040517f0bcd4ebb0000000000000000000000000000000000000000000000000000000081526001600160a01b0390911690630bcd4ebb90610a68908690600401611e15565b60206040518083038186803b158015610a8057600080fd5b505afa158015610a94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ab89190611cb5565b610ad45760405162461bcd60e51b81526004016101f090611f7a565b6040517f1f17732d0000000000000000000000000000000000000000000000000000000081526001600160a01b03851690631f17732d90610b1c908690600190600401611e5c565b600060405180830381600087803b158015610b3657600080fd5b505af1158015610b4a573d6000803e3d6000fd5b5050505050505050565b6000610b60838361170c565b80610b7357506001600160a01b03821630145b90505b92915050565b60035481565b6002546001600160a01b03163314610bac5760405162461bcd60e51b81526004016101f0906121c4565b600081118015610bbe57506003548111155b610bda5760405162461bcd60e51b81526004016101f0906123c8565b600455565b60056020526000908152604090205481565b6002546001600160a01b031681565b6060610c0c853361170c565b610c285760405162461bcd60e51b81526004016101f090611fe8565b6000856001600160a01b0316858585604051602401610c4993929190611e9a565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f8f6f03320000000000000000000000000000000000000000000000000000000017905251610cac9190611df9565b6000604051808303816000865af19150503d8060008114610ce9576040519150601f19603f3d011682016040523d82523d6000602084013e610cee565b606091505b5092509050808015610d01575060008251115b15610d215781806020019051810190610d1a9190611cd5565b9150610d4f565b815115610d32573d6000803e3d6000fd5b80610d4f5760405162461bcd60e51b81526004016101f0906120e8565b50949350505050565b6002546001600160a01b03163314610d825760405162461bcd60e51b81526004016101f0906121c4565b6040517f70a082310000000000000000000000000000000000000000000000000000000081526000906001600160a01b038316906370a0823190610dca903090600401611e15565b60206040518083038186803b158015610de257600080fd5b505afa158015610df6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e1a9190611d60565b9050816001600160a01b031663a9059cbb60e01b3383604051602401610e41929190611e29565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166001600160e01b0319909416939093179092529051610e949190611df9565b6000604051808303816000865af19150503d8060008114610ed1576040519150601f19603f3d011682016040523d82523d6000602084013e610ed6565b606091505b5050505050565b6001546040517f5a51fd430000000000000000000000000000000000000000000000000000000081526000916001600160a01b031690635a51fd4390610f299086908690600401611e42565b60206040518083038186803b158015610f4157600080fd5b505afa158015610f55573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b739190611cb5565b60086020528160005260406000208181548110610f9257fe5b9060005260206000209060089182820401919006600402915091509054906101000a900460e01b81565b6002546001600160a01b03163314610fe65760405162461bcd60e51b81526004016101f0906121c4565b6001600160a01b03811661100c5760405162461bcd60e51b81526004016101f09061245c565b6002805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0383169081179091556040517fa2ea9883a321a3e97b8266c2b078bfeec6d50c711ed71f874a90d500ae2eaf3690600090a250565b600054604051631293efbb60e21b815283916001600160a01b031690634a4fbeec90611093908490600401611e15565b60206040518083038186803b1580156110ab57600080fd5b505afa1580156110bf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110e39190611cb5565b156111005760405162461bcd60e51b81526004016101f0906120b1565b61110a833361170c565b806111a557506040517fd6eb1bbf0000000000000000000000000000000000000000000000000000000081526001600160a01b0384169063d6eb1bbf90611155903390600401611e15565b60206040518083038186803b15801561116d57600080fd5b505afa158015611181573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111a59190611cb5565b806111b557506111b583336117ab565b6111d15760405162461bcd60e51b81526004016101f09061201d565b6001600160a01b038316600090815260056020526040812054600454909181851080156111fc575082155b80156112785750856001600160a01b031663f7e80e986040518163ffffffff1660e01b815260040160206040518083038186803b15801561123c57600080fd5b505afa158015611250573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112749190611d60565b6002145b15611284575080611287565b50835b81811015801561129957506003548111155b6112b55760405162461bcd60e51b81526004016101f09061207a565b8083106112d45760405162461bcd60e51b81526004016101f0906121fb565b6001600160a01b038616600090815260056020908152604080832084905583835260089091528120905b815481101561146057600082828154811061131557fe5b600091825260209091206008820401546040517f5f54892b0000000000000000000000000000000000000000000000000000000081526004600790931683026101000a90910460e01b925030916001600160a01b038c1691635f54892b9161137f91869101611f1b565b60206040518083038186803b15801561139757600080fd5b505afa1580156113ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113cf91906119e4565b6001600160a01b031614611457576040517f13da30b20000000000000000000000000000000000000000000000000000000081526001600160a01b038a16906313da30b2906114249030908590600401611e77565b600060405180830381600087803b15801561143e57600080fd5b505af1158015611452573d6000803e3d6000fd5b505050505b506001016112fe565b506000828152600760205260408120905b815481101561155657600082828154811061148857fe5b6000918252602090912001546001600160a01b031690508615806114d057506001600160a01b03811660009081526006602090815260408083208a845290915290205460ff16155b1561154d576040517f19ab453c0000000000000000000000000000000000000000000000000000000081526001600160a01b038216906319ab453c9061151a908d90600401611e15565b600060405180830381600087803b15801561153457600080fd5b505af1158015611548573d6000803e3d6000fd5b505050505b50600101611471565b50876001600160a01b03167f9953e0e47dcd74fd932e1162859214ea7142af9a476c782f129af1f3a5843ebd846040516115909190612493565b60405180910390a25050505050505050565b6115ac843361170c565b6115c85760405162461bcd60e51b81526004016101f0906123ff565b6115d3848383611839565b6115ef5760405162461bcd60e51b81526004016101f090612156565b6001600160a01b0383166000908152600a602052604090205460ff166116275760405162461bcd60e51b81526004016101f090611fb1565b6000836001600160a01b03168383604051611643929190611de9565b6000604051808303816000865af19150503d8060008114611680576040519150601f19603f3d011682016040523d82523d6000602084013e611685565b606091505b5050905080610ed65760405162461bcd60e51b81526004016101f09061211f565b60045481565b606090565b600760205281600052604060002081815481106116ca57fe5b6000918252602090912001546001600160a01b03169150829050565b60096020908152600092835260408084209091529082529020546001600160a01b031681565b6001600160a01b038082166000908152600660209081526040808320938616835260058252808320548352929052205460ff1692915050565b60006004825110156117695760405162461bcd60e51b81526004016101f09061218d565b506020015190565b61177b8282610edd565b8061178b575061178b82826117ab565b6117a75760405162461bcd60e51b81526004016101f0906122fd565b5050565b6000816001600160a01b0316836001600160a01b0316638da5cb5b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156117f057600080fd5b505afa158015611804573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061182891906119e4565b6001600160a01b0316149392505050565b6000602482101561185c5760405162461bcd60e51b81526004016101f090612232565b600061186b8360048187612571565b81019061187891906119c1565b6001600160a01b03908116908616149150509392505050565b8280548282559060005260206000209081019282156118f1579160200282015b828111156118f157815473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b038435161782556020909201916001909101906118b1565b506118fd929150611901565b5090565b5b808211156118fd57805473ffffffffffffffffffffffffffffffffffffffff19168155600101611902565b60008083601f84011261193e578182fd5b50813567ffffffffffffffff811115611955578182fd5b602083019150836020808302850101111561196f57600080fd5b9250929050565b8051610b76816125de565b60008083601f840112611992578182fd5b50813567ffffffffffffffff8111156119a9578182fd5b60208301915083602082850101111561196f57600080fd5b6000602082840312156119d2578081fd5b81356119dd816125c9565b9392505050565b6000602082840312156119f5578081fd5b81516119dd816125c9565b60008060408385031215611a12578081fd5b8235611a1d816125c9565b91506020830135611a2d816125c9565b809150509250929050565b60008060008060608587031215611a4d578182fd5b8435611a58816125c9565b93506020850135611a68816125c9565b9250604085013567ffffffffffffffff811115611a83578283fd5b611a8f87828801611981565b95989497509550505050565b60008060008060808587031215611ab0578384fd5b8435611abb816125c9565b93506020850135611acb816125c9565b925060408501359150606085013567ffffffffffffffff811115611aed578182fd5b8501601f81018713611afd578182fd5b8035611b10611b0b8261254d565b612506565b818152886020838501011115611b24578384fd5b81602084016020830137908101602001929092525092959194509250565b600080600060408486031215611b56578283fd5b8335611b61816125c9565b9250602084013567ffffffffffffffff811115611b7c578283fd5b611b8886828701611981565b9497909650939450505050565b60008060408385031215611ba7578182fd5b8235611bb2816125c9565b946020939093013593505050565b60008060008060408587031215611bd5578384fd5b843567ffffffffffffffff80821115611bec578586fd5b611bf88883890161192d565b90965094506020870135915080821115611c10578384fd5b50611a8f8782880161192d565b60006020808385031215611c2f578182fd5b825167ffffffffffffffff811115611c45578283fd5b8301601f81018513611c55578283fd5b8051611c63611b0b8261252d565b8181528381019083850185840285018601891015611c7f578687fd5b8694505b83851015611ca957611c958982611976565b835260019490940193918501918501611c83565b50979650505050505050565b600060208284031215611cc6578081fd5b815180151581146119dd578182fd5b600060208284031215611ce6578081fd5b815167ffffffffffffffff811115611cfc578182fd5b8201601f81018413611d0c578182fd5b8051611d1a611b0b8261254d565b818152856020838501011115611d2e578384fd5b611d3f826020830160208601612599565b95945050505050565b600060208284031215611d59578081fd5b5035919050565b600060208284031215611d71578081fd5b5051919050565b60008060408385031215611d8a578182fd5b823591506020830135611a2d816125de565b60008060408385031215611dae578182fd5b50508035926020909101359150565b60008151808452611dd5816020860160208601612599565b601f01601f19169290920160200192915050565b6000828483379101908152919050565b60008251611e0b818460208701612599565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039290921682521515602082015260400190565b6001600160a01b039290921682526001600160e01b031916602082015260400190565b60006001600160a01b038516825283602083015260606040830152611d3f6060830184611dbd565b6020808252825182820181905260009190848201906040850190845b81811015611f045783516001600160e01b03191683529284019291840191600101611ede565b50909695505050505050565b901515815260200190565b6001600160e01b031991909116815260200190565b600060208252610b736020830184611dbd565b60208082526012908201527f564d3a20756e6b6e6f776e206d6574686f640000000000000000000000000000604082015260600190565b6020808252601c908201527f564d3a206d6f64756c65206973206e6f74207265676973746572656400000000604082015260600190565b6020808252601b908201527f564d3a20696e76616c69642073746f7261676520696e766f6b65640000000000604082015260600190565b6020808252818101527f564d3a2073656e646572206d6179206e6f7420696e766f6b652077616c6c6574604082015260600190565b60208082526021908201527f564d3a2073656e646572206d6179206e6f7420757067726164652077616c6c6560408201527f7400000000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526016908201527f564d3a20696e76616c6964205f746f56657273696f6e00000000000000000000604082015260600190565b60208082526011908201527f42463a2077616c6c6574206c6f636b6564000000000000000000000000000000604082015260600190565b6020808252601a908201527f564d3a2077616c6c657420696e766f6b65207265766572746564000000000000604082015260600190565b60208082526013908201527f564d3a205f73746f72616765206661696c656400000000000000000000000000604082015260600190565b6020808252601e908201527f564d3a20746172676574206f66205f6461746120213d205f77616c6c65740000604082015260600190565b6020808252601a908201527f524d3a20496e76616c69642066756e6374696f6e507265666978000000000000604082015260600190565b6020808252600d908201527f4d757374206265206f776e657200000000000000000000000000000000000000604082015260600190565b6020808252601a908201527f564d3a20616c7265616479206f6e206e65772076657273696f6e000000000000604082015260600190565b60208082526016908201527f524d3a20496e76616c6964206461746157616c6c657400000000000000000000604082015260600190565b60208082526019908201527f564d3a2073746f7261676520616c726561647920616464656400000000000000604082015260600190565b60208082526027908201527f564d3a2073656e6465722073686f756c6420626520617574686f72697a65642060408201527f6665617475726500000000000000000000000000000000000000000000000000606082015260800190565b6020808252601c908201527f42463a206d757374206265206f776e6572206f72206665617475726500000000604082015260600190565b60208082526030908201527f564d3a207374617469632063616c6c206e6f7420737570706f7274656420666f60408201527f722077616c6c65742076657273696f6e00000000000000000000000000000000606082015260800190565b6020808252601b908201527f564d3a20696e76616c6964205f6665617475726573546f496e69740000000000604082015260600190565b60208082526017908201527f564d3a20696e76616c6964205f6d696e56657273696f6e000000000000000000604082015260600190565b60208082526021908201527f564d3a2073656e646572206d6179206e6f7420696e766f6b652073746f72616760408201527f6500000000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526018908201527f41646472657373206d757374206e6f74206265206e756c6c0000000000000000604082015260600190565b90815260200190565b83815260406020808301829052908201839052600090849060608401835b86811015611ca95783356124cd816125c9565b6001600160a01b0316825292820192908201906001016124ba565b82815260408101600483106124f957fe5b8260208301529392505050565b60405181810167ffffffffffffffff8111828210171561252557600080fd5b604052919050565b600067ffffffffffffffff821115612543578081fd5b5060209081020190565b600067ffffffffffffffff821115612563578081fd5b50601f01601f191660200190565b60008085851115612580578182fd5b8386111561258c578182fd5b5050820193919092039150565b60005b838110156125b457818101518382015260200161259c565b838111156125c3576000848401525b50505050565b6001600160a01b03811681146107e257600080fd5b6001600160e01b0319811681146107e257600080fdfea26469706673582212202ee8a1e424f948094acae2602d92f1c87ca93a5b44ca6cd98a56e93777d7871f64736f6c634300060c0033
[ 8 ]
0x4b44D2aB801D0C0160e75bcA17B08637e5d8e113
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface sbCommunityInterface { function getTokenData(address token, uint256 day) external view returns ( uint256, uint256, uint256 ); function receiveRewards(uint256 day, uint256 amount) external; function serviceAccepted(address service) external view returns (bool); function getMinerRewardPercentage() external view returns (uint256); } interface sbControllerInterface { function getDayMineSecondsUSDTotal(uint256 day) external view returns (uint256); function getCommunityDayMineSecondsUSD(address community, uint256 day) external view returns (uint256); function getCommunityDayRewards(address community, uint256 day) external view returns (uint256); function getStartDay() external view returns (uint256); function getMaxYears() external view returns (uint256); function getStrongPoolDailyRewards(uint256 day) external view returns (uint256); function communityAccepted(address community) external view returns (bool); function getCommunities() external view returns (address[] memory); function upToDate() external view returns (bool); } interface sbStrongPoolInterface { function serviceMinMined(address miner) external view returns (bool); function minerMinMined(address miner) external view returns (bool); function mineFor(address miner, uint256 amount) external; function getMineData(uint256 day) external view returns ( uint256, uint256, uint256 ); function receiveRewards(uint256 day, uint256 amount) external; } contract sbVotes { event VotesUpdated(address indexed voter, uint256 amount, bool indexed adding); event RewardsReceivedForCommunity(address indexed community, uint256 indexed day, uint256 amount); event RewardsReceivedForVoters(uint256 indexed day, uint256 amount); event Voted(address indexed voter, address community, address indexed service, uint256 amount, uint256 indexed day); event VoteRecalled( address indexed voter, address community, address indexed service, uint256 amount, uint256 indexed day ); event ServiceDropped(address indexed voter, address community, address indexed service, uint256 indexed day); event Claimed(address indexed service, uint256 amount, uint256 indexed day); using SafeMath for uint256; bool internal initDone; sbControllerInterface internal sbController; sbStrongPoolInterface internal sbStrongPool; IERC20 internal strongToken; mapping(address => uint96) internal balances; mapping(address => address) public delegates; struct Checkpoint { uint32 fromBlock; uint96 votes; } mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; mapping(address => uint32) public numCheckpoints; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); event AddVotes(address indexed staker, uint256 amount); event SubVotes(address indexed staker, uint256 amount); mapping(address => mapping(address => address[])) internal voterCommunityServices; mapping(address => mapping(address => mapping(address => uint256[]))) internal voterCommunityServiceDays; mapping(address => mapping(address => mapping(address => uint256[]))) internal voterCommunityServiceAmounts; mapping(address => mapping(address => mapping(address => uint256[]))) internal voterCommunityServiceVoteSeconds; mapping(address => uint256) internal voterDayLastClaimedFor; mapping(address => uint256) internal voterVotesOut; mapping(uint256 => uint256) internal dayVoterRewards; mapping(address => mapping(address => uint256[])) internal serviceCommunityDays; mapping(address => mapping(address => uint256[])) internal serviceCommunityAmounts; mapping(address => mapping(address => uint256[])) internal serviceCommunityVoteSeconds; mapping(address => uint256) internal serviceDayLastClaimedFor; mapping(address => uint256[]) internal communityDays; mapping(address => uint256[]) internal communityAmounts; mapping(address => uint256[]) internal communityVoteSeconds; mapping(address => mapping(uint256 => uint256)) internal communityDayRewards; function init( address sbControllerAddress, address sbStrongPoolAddress, address strongTokenAddress ) public { require(!initDone, 'init done'); sbController = sbControllerInterface(sbControllerAddress); sbStrongPool = sbStrongPoolInterface(sbStrongPoolAddress); strongToken = IERC20(strongTokenAddress); initDone = true; } function updateVotes( address voter, uint256 rawAmount, bool adding ) external { require(msg.sender == address(sbStrongPool), 'not sbStrongPool'); uint96 amount = _safe96(rawAmount, 'amount exceeds 96 bits'); if (adding) { _addVotes(voter, amount); } else { require(voter == delegates[voter], 'must delegate to self'); require(_getAvailableServiceVotes(voter) >= amount, 'must recall votes'); _subVotes(voter, amount); } emit VotesUpdated(voter, amount, adding); } function getCurrentProposalVotes(address account) external view returns (uint96) { return _getCurrentProposalVotes(account); } function getPriorProposalVotes(address account, uint256 blockNumber) external view returns (uint96) { require(blockNumber < block.number, 'not yet determined'); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function getCommunityData(address community, uint256 day) external view returns ( uint256, uint256, uint256 ) { require(sbController.communityAccepted(community), 'invalid community'); require(day <= _getCurrentDay(), 'invalid day'); return _getCommunityData(community, day); } function receiveServiceRewards(uint256 day, uint256 amount) external { require(amount > 0, 'zero'); require(sbController.communityAccepted(msg.sender), 'invalid community'); strongToken.transferFrom(msg.sender, address(this), amount); communityDayRewards[msg.sender][day] = communityDayRewards[msg.sender][day].add(amount); emit RewardsReceivedForCommunity(msg.sender, day, amount); } function receiveVoterRewards(uint256 day, uint256 amount) external { require(amount > 0, 'zero'); require(msg.sender == address(sbController), 'not sbController'); strongToken.transferFrom(msg.sender, address(this), amount); dayVoterRewards[day] = dayVoterRewards[day].add(amount); emit RewardsReceivedForVoters(day, amount); } function getServiceDayLastClaimedFor(address service) public view returns (uint256) { return serviceDayLastClaimedFor[service] == 0 ? sbController.getStartDay().sub(1) : serviceDayLastClaimedFor[service]; } function getVoterDayLastClaimedFor(address voter) public view returns (uint256) { return voterDayLastClaimedFor[voter] == 0 ? sbController.getStartDay().sub(1) : voterDayLastClaimedFor[voter]; } function getSbControllerAddressUsed() public view returns (address) { return address(sbController); } function getSbStrongPoolAddressUsed() public view returns (address) { return address(sbStrongPool); } function getStrongAddressUsed() public view returns (address) { return address(strongToken); } function getCommunityDayRewards(address community, uint256 day) public view returns (uint256) { require(sbController.communityAccepted(community), 'invalid community'); require(day <= _getCurrentDay(), 'invalid day'); return communityDayRewards[community][day]; } function getDayVoterRewards(uint256 day) public view returns (uint256) { require(day <= _getCurrentDay(), 'invalid day'); return dayVoterRewards[day]; } function recallAllVotes() public { require(voterVotesOut[msg.sender] > 0, 'no votes out'); _recallAllVotes((msg.sender)); } function delegate(address delegatee) public { address currentDelegate = delegates[msg.sender]; if (currentDelegate != delegatee && voterVotesOut[currentDelegate] > 0) { _recallAllVotes(currentDelegate); } _delegate(msg.sender, delegatee); } function getDelegate(address delegator) public view returns (address) { return delegates[delegator]; } function getAvailableServiceVotes(address account) public view returns (uint96) { return _getAvailableServiceVotes(account); } function getVoterCommunityServices(address voter, address community) public view returns (address[] memory) { require(sbController.communityAccepted(community), 'invalid community'); return voterCommunityServices[voter][community]; } function vote( address community, address service, uint256 amount ) public { require(amount > 0, '1: zero'); require(sbController.communityAccepted(community), 'invalid community'); require(100 - sbCommunityInterface(community).getMinerRewardPercentage() != 0, '2: zero.'); require(sbCommunityInterface(community).serviceAccepted(service), 'invalid service'); require(sbStrongPool.serviceMinMined(service), 'not min mined'); require(voterCommunityServices[msg.sender][community].length < 10, 'limit met'); require(uint256(_getAvailableServiceVotes(msg.sender)) >= amount, 'not enough votes'); if (!_voterCommunityServiceExists(msg.sender, community, service)) { voterCommunityServices[msg.sender][community].push(service); } uint256 currentDay = _getCurrentDay(); _updateVoterCommunityServiceData(msg.sender, community, service, amount, true, currentDay); _updateServiceCommunityData(service, community, amount, true, currentDay); _updateCommunityData(community, amount, true, currentDay); voterVotesOut[msg.sender] = voterVotesOut[msg.sender].add(amount); emit Voted(msg.sender, community, service, amount, currentDay); } function recallVote( address community, address service, uint256 amount ) public { require(amount > 0, 'zero'); require(sbController.communityAccepted(community), 'invalid community'); require(sbCommunityInterface(community).serviceAccepted(service), 'invalid service'); require(_voterCommunityServiceExists(msg.sender, community, service), 'not found'); uint256 currentDay = _getCurrentDay(); (, uint256 votes, ) = _getVoterCommunityServiceData(msg.sender, community, service, currentDay); require(votes >= amount, 'not enough votes'); _updateVoterCommunityServiceData(msg.sender, community, service, amount, false, currentDay); _updateServiceCommunityData(service, community, amount, false, currentDay); _updateCommunityData(community, amount, false, currentDay); voterVotesOut[msg.sender] = voterVotesOut[msg.sender].sub(amount); emit VoteRecalled(msg.sender, community, service, amount, currentDay); } function dropService(address community, address service) public { require(sbController.communityAccepted(community), 'invalid community'); require(sbCommunityInterface(community).serviceAccepted(service), 'invalid service'); require(_voterCommunityServiceExists(msg.sender, community, service), 'not found'); uint256 currentDay = _getCurrentDay(); (, uint256 votes, ) = _getVoterCommunityServiceData(msg.sender, community, service, currentDay); _updateVoterCommunityServiceData(msg.sender, community, service, votes, false, currentDay); _updateServiceCommunityData(service, community, votes, false, currentDay); _updateCommunityData(community, votes, false, currentDay); voterVotesOut[msg.sender] = voterVotesOut[msg.sender].sub(votes); uint256 index = _findIndexOfAddress(voterCommunityServices[msg.sender][community], service); _deleteArrayElement(index, voterCommunityServices[msg.sender][community]); emit ServiceDropped(msg.sender, community, service, currentDay); } function serviceClaimAll() public { uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = serviceDayLastClaimedFor[msg.sender] == 0 ? sbController.getStartDay().sub(1) : serviceDayLastClaimedFor[msg.sender]; require(currentDay > dayLastClaimedFor.add(7), 'already claimed'); require(sbController.upToDate(), 'need rewards released'); require(sbStrongPool.serviceMinMined(msg.sender), 'not min mined'); _serviceClaim(currentDay, msg.sender, dayLastClaimedFor); } function serviceClaimUpTo(uint256 day) public { require(day <= _getCurrentDay(), 'invalid day'); uint256 dayLastClaimedFor = serviceDayLastClaimedFor[msg.sender] == 0 ? sbController.getStartDay().sub(1) : serviceDayLastClaimedFor[msg.sender]; require(day > dayLastClaimedFor.add(7), 'already claimed'); require(sbController.upToDate(), 'need rewards released'); require(sbStrongPool.serviceMinMined(msg.sender), 'not min mined'); _serviceClaim(day, msg.sender, dayLastClaimedFor); } function voterClaimAll() public { uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = voterDayLastClaimedFor[msg.sender] == 0 ? sbController.getStartDay().sub(1) : voterDayLastClaimedFor[msg.sender]; require(currentDay > dayLastClaimedFor.add(7), 'already claimed'); require(sbController.upToDate(), 'need rewards released'); _voterClaim(currentDay, msg.sender, dayLastClaimedFor); } function voterClaimUpTo(uint256 day) public { require(day <= _getCurrentDay(), 'invalid day'); uint256 dayLastClaimedFor = voterDayLastClaimedFor[msg.sender] == 0 ? sbController.getStartDay().sub(1) : voterDayLastClaimedFor[msg.sender]; require(day > dayLastClaimedFor.add(7), 'already claimed'); require(sbController.upToDate(), 'need rewards released'); _voterClaim(day, msg.sender, dayLastClaimedFor); } function getServiceRewardsDueAll(address service) public view returns (uint256) { uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = serviceDayLastClaimedFor[service] == 0 ? sbController.getStartDay().sub(1) : serviceDayLastClaimedFor[service]; if (!(currentDay > dayLastClaimedFor.add(7))) { return 0; } require(sbController.upToDate(), 'need rewards released'); return _getServiceRewardsDue(currentDay, service, dayLastClaimedFor); } function getServiceRewardsDueUpTo(uint256 day, address service) public view returns (uint256) { require(day <= _getCurrentDay(), 'invalid day'); uint256 dayLastClaimedFor = serviceDayLastClaimedFor[service] == 0 ? sbController.getStartDay().sub(1) : serviceDayLastClaimedFor[service]; if (!(day > dayLastClaimedFor.add(7))) { return 0; } require(sbController.upToDate(), 'need rewards released'); return _getServiceRewardsDue(day, service, dayLastClaimedFor); } function getVoterRewardsDueAll(address voter) public view returns (uint256) { uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = voterDayLastClaimedFor[voter] == 0 ? sbController.getStartDay().sub(1) : voterDayLastClaimedFor[voter]; if (!(currentDay > dayLastClaimedFor.add(7))) { return 0; } require(sbController.upToDate(), 'need rewards released'); return _getVoterRewardsDue(currentDay, voter, dayLastClaimedFor); } function getVoterRewardsDueUpTo(uint256 day, address voter) public view returns (uint256) { require(day <= _getCurrentDay(), 'invalid day'); uint256 dayLastClaimedFor = voterDayLastClaimedFor[voter] == 0 ? sbController.getStartDay().sub(1) : voterDayLastClaimedFor[voter]; if (!(day > dayLastClaimedFor.add(7))) { return 0; } require(sbController.upToDate(), 'need rewards released'); return _getVoterRewardsDue(day, voter, dayLastClaimedFor); } function getVoterCommunityServiceData( address voter, address community, address service, uint256 day ) public view returns ( uint256, uint256, uint256 ) { require(sbController.communityAccepted(community), 'invalid community'); require(sbCommunityInterface(community).serviceAccepted(service), 'invalid service'); if (!_voterCommunityServiceExists(voter, community, service)) { return (day, 0, 0); } require(day <= _getCurrentDay(), 'invalid day'); return _getVoterCommunityServiceData(voter, community, service, day); } function getServiceCommunityData( address service, address community, uint256 day ) public view returns ( uint256, uint256, uint256 ) { require(sbController.communityAccepted(community), 'invalid community'); require(sbCommunityInterface(community).serviceAccepted(service), 'invalid service'); require(day <= _getCurrentDay(), 'invalid day'); return _getServiceCommunityData(service, community, day); } function _getVoterCommunityServiceData( address voter, address community, address service, uint256 day ) internal view returns ( uint256, uint256, uint256 ) { uint256[] memory _Days = voterCommunityServiceDays[voter][community][service]; uint256[] memory _Amounts = voterCommunityServiceAmounts[voter][community][service]; uint256[] memory _UnitSeconds = voterCommunityServiceVoteSeconds[voter][community][service]; return _get(_Days, _Amounts, _UnitSeconds, day); } function _getServiceCommunityData( address service, address community, uint256 day ) internal view returns ( uint256, uint256, uint256 ) { uint256[] memory _Days = serviceCommunityDays[service][community]; uint256[] memory _Amounts = serviceCommunityAmounts[service][community]; uint256[] memory _UnitSeconds = serviceCommunityVoteSeconds[service][community]; return _get(_Days, _Amounts, _UnitSeconds, day); } function _getCommunityData(address community, uint256 day) internal view returns ( uint256, uint256, uint256 ) { uint256[] memory _Days = communityDays[community]; uint256[] memory _Amounts = communityAmounts[community]; uint256[] memory _UnitSeconds = communityVoteSeconds[community]; return _get(_Days, _Amounts, _UnitSeconds, day); } function _updateVoterCommunityServiceData( address voter, address community, address service, uint256 amount, bool adding, uint256 currentDay ) internal { uint256[] storage _Days = voterCommunityServiceDays[voter][community][service]; uint256[] storage _Amounts = voterCommunityServiceAmounts[voter][community][service]; uint256[] storage _UnitSeconds = voterCommunityServiceVoteSeconds[voter][community][service]; _update(_Days, _Amounts, _UnitSeconds, amount, adding, currentDay); } function _updateServiceCommunityData( address service, address community, uint256 amount, bool adding, uint256 currentDay ) internal { uint256[] storage _Days = serviceCommunityDays[service][community]; uint256[] storage _Amounts = serviceCommunityAmounts[service][community]; uint256[] storage _UnitSeconds = serviceCommunityVoteSeconds[service][community]; _update(_Days, _Amounts, _UnitSeconds, amount, adding, currentDay); } function _updateCommunityData( address community, uint256 amount, bool adding, uint256 currentDay ) internal { uint256[] storage _Days = communityDays[community]; uint256[] storage _Amounts = communityAmounts[community]; uint256[] storage _UnitSeconds = communityVoteSeconds[community]; _update(_Days, _Amounts, _UnitSeconds, amount, adding, currentDay); } function _get( uint256[] memory _Days, uint256[] memory _Amounts, uint256[] memory _UnitSeconds, uint256 day ) internal pure returns ( uint256, uint256, uint256 ) { uint256 len = _Days.length; if (len == 0) { return (day, 0, 0); } if (day < _Days[0]) { return (day, 0, 0); } uint256 lastIndex = len.sub(1); uint256 lastMinedDay = _Days[lastIndex]; if (day == lastMinedDay) { return (day, _Amounts[lastIndex], _UnitSeconds[lastIndex]); } else if (day > lastMinedDay) { return (day, _Amounts[lastIndex], _Amounts[lastIndex].mul(1 days)); } return _find(_Days, _Amounts, _UnitSeconds, day); } function _find( uint256[] memory _Days, uint256[] memory _Amounts, uint256[] memory _UnitSeconds, uint256 day ) internal pure returns ( uint256, uint256, uint256 ) { uint256 left = 0; uint256 right = _Days.length.sub(1); uint256 middle = right.add(left).div(2); while (left < right) { if (_Days[middle] == day) { return (day, _Amounts[middle], _UnitSeconds[middle]); } else if (_Days[middle] > day) { if (middle > 0 && _Days[middle.sub(1)] < day) { return (day, _Amounts[middle.sub(1)], _Amounts[middle.sub(1)].mul(1 days)); } if (middle == 0) { return (day, 0, 0); } right = middle.sub(1); } else if (_Days[middle] < day) { if (middle < _Days.length.sub(1) && _Days[middle.add(1)] > day) { return (day, _Amounts[middle], _Amounts[middle].mul(1 days)); } left = middle.add(1); } middle = right.add(left).div(2); } if (_Days[middle] != day) { return (day, 0, 0); } else { return (day, _Amounts[middle], _UnitSeconds[middle]); } } function _update( uint256[] storage _Days, uint256[] storage _Amounts, uint256[] storage _UnitSeconds, uint256 amount, bool adding, uint256 currentDay ) internal { uint256 len = _Days.length; uint256 secondsInADay = 1 days; uint256 secondsSinceStartOfDay = block.timestamp % secondsInADay; uint256 secondsUntilEndOfDay = secondsInADay.sub(secondsSinceStartOfDay); if (len == 0) { if (adding) { _Days.push(currentDay); _Amounts.push(amount); _UnitSeconds.push(amount.mul(secondsUntilEndOfDay)); } else { require(false, '1: not enough mine'); } } else { uint256 lastIndex = len.sub(1); uint256 lastMinedDay = _Days[lastIndex]; uint256 lastMinedAmount = _Amounts[lastIndex]; uint256 lastUnitSeconds = _UnitSeconds[lastIndex]; uint256 newAmount; uint256 newUnitSeconds; if (lastMinedDay == currentDay) { if (adding) { newAmount = lastMinedAmount.add(amount); newUnitSeconds = lastUnitSeconds.add(amount.mul(secondsUntilEndOfDay)); } else { require(lastMinedAmount >= amount, '2: not enough mine'); newAmount = lastMinedAmount.sub(amount); newUnitSeconds = lastUnitSeconds.sub(amount.mul(secondsUntilEndOfDay)); } _Amounts[lastIndex] = newAmount; _UnitSeconds[lastIndex] = newUnitSeconds; } else { if (adding) { newAmount = lastMinedAmount.add(amount); newUnitSeconds = lastMinedAmount.mul(1 days).add(amount.mul(secondsUntilEndOfDay)); } else { require(lastMinedAmount >= amount, '3: not enough mine'); newAmount = lastMinedAmount.sub(amount); newUnitSeconds = lastMinedAmount.mul(1 days).sub(amount.mul(secondsUntilEndOfDay)); } _Days.push(currentDay); _Amounts.push(newAmount); _UnitSeconds.push(newUnitSeconds); } } } function _addVotes(address voter, uint96 amount) internal { require(voter != address(0), 'zero address'); balances[voter] = _add96(balances[voter], amount, 'vote amount overflows'); _addDelegates(voter, amount); emit AddVotes(voter, amount); } function _subVotes(address voter, uint96 amount) internal { balances[voter] = _sub96(balances[voter], amount, 'vote amount exceeds balance'); _subtactDelegates(voter, amount); emit SubVotes(voter, amount); } function _addDelegates(address staker, uint96 amount) internal { if (delegates[staker] == address(0)) { delegates[staker] = staker; } address currentDelegate = delegates[staker]; _moveDelegates(address(0), currentDelegate, amount); } function _subtactDelegates(address staker, uint96 amount) internal { address currentDelegate = delegates[staker]; _moveDelegates(currentDelegate, address(0), amount); } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = _sub96(srcRepOld, amount, 'vote amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = _add96(dstRepOld, amount, 'vote amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = _safe32(block.number, 'block number exceeds 32 bits'); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function _safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function _add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function _sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function _getCurrentProposalVotes(address account) internal view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function _getAvailableServiceVotes(address account) internal view returns (uint96) { uint96 proposalVotes = _getCurrentProposalVotes(account); return proposalVotes == 0 ? 0 : proposalVotes - _safe96(voterVotesOut[account], 'voterVotesOut exceeds 96 bits'); } function _voterCommunityServiceExists( address voter, address community, address service ) internal view returns (bool) { for (uint256 i = 0; i < voterCommunityServices[voter][community].length; i++) { if (voterCommunityServices[voter][community][i] == service) { return true; } } return false; } function _recallAllVotes(address voter) internal { uint256 currentDay = _getCurrentDay(); address[] memory communities = sbController.getCommunities(); for (uint256 i = 0; i < communities.length; i++) { address community = communities[i]; address[] memory services = voterCommunityServices[voter][community]; for (uint256 j = 0; j < services.length; j++) { address service = services[j]; (, uint256 amount, ) = _getVoterCommunityServiceData(voter, community, service, currentDay); _updateVoterCommunityServiceData(msg.sender, community, service, amount, false, currentDay); _updateServiceCommunityData(service, community, amount, false, currentDay); _updateCommunityData(community, amount, false, currentDay); voterVotesOut[msg.sender] = voterVotesOut[msg.sender].sub(amount); } } } function _serviceClaim( uint256 upToDay, address service, uint256 dayLastClaimedFor ) internal { uint256 rewards = _getServiceRewardsDue(upToDay, service, dayLastClaimedFor); require(rewards > 0, 'no rewards'); serviceDayLastClaimedFor[service] = upToDay.sub(7); strongToken.approve(address(sbStrongPool), rewards); sbStrongPool.mineFor(service, rewards); emit Claimed(service, rewards, _getCurrentDay()); } function _getServiceRewardsDue( uint256 upToDay, address service, uint256 dayLastClaimedFor ) internal view returns (uint256) { uint256 rewards; for (uint256 day = dayLastClaimedFor.add(1); day <= upToDay.sub(7); day++) { address[] memory communities = sbController.getCommunities(); for (uint256 i = 0; i < communities.length; i++) { address community = communities[i]; (, , uint256 communityVoteSecondsForDay) = _getCommunityData(community, day); if (communityVoteSecondsForDay == 0) { continue; } (, , uint256 serviceVoteSeconds) = _getServiceCommunityData(service, community, day); uint256 availableRewards = communityDayRewards[community][day]; uint256 amount = availableRewards.mul(serviceVoteSeconds).div(communityVoteSecondsForDay); rewards = rewards.add(amount); } } return rewards; } function _voterClaim( uint256 upToDay, address voter, uint256 dayLastClaimedFor ) internal { uint256 rewards = _getVoterRewardsDue(upToDay, voter, dayLastClaimedFor); require(rewards > 0, 'no rewards'); voterDayLastClaimedFor[voter] = upToDay.sub(7); strongToken.approve(address(sbStrongPool), rewards); sbStrongPool.mineFor(voter, rewards); emit Claimed(voter, rewards, _getCurrentDay()); } function _getVoterRewardsDue( uint256 upToDay, address voter, uint256 dayLastClaimedFor ) internal view returns (uint256) { uint256 rewards; for (uint256 day = dayLastClaimedFor.add(1); day <= upToDay.sub(7); day++) { address[] memory communities = sbController.getCommunities(); for (uint256 i = 0; i < communities.length; i++) { address community = communities[i]; (, , uint256 communityVoteSecondsForDay) = _getCommunityData(community, day); if (communityVoteSecondsForDay == 0) { continue; } address[] memory services = voterCommunityServices[voter][community]; uint256 voterCommunityVoteSeconds; for (uint256 j = 0; j < services.length; j++) { address service = services[j]; (, , uint256 voterVoteSeconds) = _getVoterCommunityServiceData(voter, community, service, day); voterCommunityVoteSeconds = voterCommunityVoteSeconds.add(voterVoteSeconds); } uint256 availableRewards = dayVoterRewards[day]; uint256 amount = availableRewards.mul(voterCommunityVoteSeconds).div(communityVoteSecondsForDay); rewards = rewards.add(amount); } } return rewards; } function _getCurrentDay() internal view returns (uint256) { return block.timestamp.div(1 days).add(1); } function _deleteArrayElement(uint256 index, address[] storage array) internal { if (index == array.length.sub(1)) { array.pop(); } else { array[index] = array[array.length.sub(1)]; delete array[array.length.sub(1)]; array.pop(); } } function _findIndexOfAddress(address[] memory array, address element) internal pure returns (uint256) { uint256 index; for (uint256 i = 0; i < array.length; i++) { if (array[i] == element) { index = i; } } return index; } }
0x608060405234801561001057600080fd5b50600436106102115760003560e01c8063916c435f11610125578063c5307a00116100ad578063f0d78bf51161007c578063f0d78bf514610474578063f1127ed814610487578063f3eb13e8146104a8578063fc0e2e29146104b0578063fd50f31d146104c357610211565b8063c5307a0014610433578063c9ff857214610446578063d32028301461044e578063efa5d4311461046157610211565b8063aa40f500116100f4578063aa40f500146103df578063b46377a0146103f2578063b5e3ee50146103fa578063b8b82afa1461040d578063c1dbe8631461042057610211565b8063916c435f146103865780639fb9ec11146103a6578063a4cb05b9146103b9578063a73e935a146103cc57610211565b80635c19a95c116101a8578063733fb91f11610177578063733fb91f14610332578063820efe461461033a57806389096b391461034d5780638f288a091461036057806390a39a9e1461037357610211565b80635c19a95c146102d757806365a4840d146102ea5780636a33bc13146102f25780636fcfff451461031257610211565b8063242be821116101e4578063242be8211461028b578063360358be1461029e578063544d8564146102b1578063587cde1e146102c457610211565b806304a3379f14610216578063054059d814610234578063184b9559146102545780631dae093814610269575b600080fd5b61021e6104d6565b60405161022b9190614946565b60405180910390f35b610247610242366004614662565b6104e5565b60405161022b9190614997565b61026761026236600461469a565b610612565b005b61027c610277366004614774565b61068b565b60405161022b93929190614e72565b610267610299366004614925565b61076e565b6102676102ac366004614734565b6108ad565b61021e6102bf366004614646565b610b10565b61021e6102d2366004614646565b610b31565b6102676102e5366004614646565b610b4c565b610267610bac565b610305610300366004614646565b610d4d565b60405161022b9190614e69565b610325610320366004614646565b610ddc565b60405161022b9190614e88565b61021e610df4565b610305610348366004614646565b610e03565b61027c61035b366004614734565b610f74565b61026761036e366004614662565b6110f2565b610305610381366004614774565b6113b3565b610399610394366004614774565b6114a4565b60405161022b9190614eb8565b6102676103b436600461479f565b6116b2565b6103056103c73660046148d1565b6117f5565b6103996103da366004614646565b611831565b6103996103ed366004614646565b61183c565b610267611847565b6102676104083660046148d1565b61187e565b61027c61041b3660046146e4565b6118cf565b61026761042e3660046148d1565b611a6d565b610267610441366004614925565b611c85565b61021e611e4f565b61030561045c366004614901565b611e63565b61026761046f366004614734565b611fe5565b610305610482366004614646565b6123e8565b61049a6104953660046147d5565b612551565b60405161022b929190614e99565b610267612586565b6103056104be366004614646565b6125be565b6103056104d1366004614901565b6125fa565b6002546001600160a01b031690565b6000546040516305c9ea6360e21b815260609161010090046001600160a01b031690631727a98c9061051b908590600401614946565b60206040518083038186803b15801561053357600080fd5b505afa158015610547573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061056b91906148b5565b6105905760405162461bcd60e51b815260040161058790614d0e565b60405180910390fd5b6001600160a01b0380841660009081526007602090815260408083209386168352928152908290208054835181840281018401909452808452909183018282801561060457602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116105e6575b505050505090505b92915050565b60005460ff16156106355760405162461bcd60e51b815260040161058790614c78565b60008054600180546001600160a01b03199081166001600160a01b039687161782556002805490911694861694909417909355610100600160a81b03191661010094909316939093029190911760ff1916179055565b600080546040516305c9ea6360e21b8152829182916101009091046001600160a01b031690631727a98c906106c4908890600401614946565b60206040518083038186803b1580156106dc57600080fd5b505afa1580156106f0573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061071491906148b5565b6107305760405162461bcd60e51b815260040161058790614d0e565b61073861277c565b8411156107575760405162461bcd60e51b815260040161058790614ab4565b610761858561279b565b9250925092509250925092565b6000811161078e5760405162461bcd60e51b815260040161058790614b2c565b60005461010090046001600160a01b031633146107bd5760405162461bcd60e51b815260040161058790614b02565b6002546040516323b872dd60e01b81526001600160a01b03909116906323b872dd906107f19033903090869060040161495a565b602060405180830381600087803b15801561080b57600080fd5b505af115801561081f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061084391906148b5565b506000828152600d602052604090205461085d90826128f8565b6000838152600d602052604090819020919091555182907f5f5f9298130e00d274171e6e8b2aa65a68088ff30d640384937a655f65c87dc2906108a1908490614e69565b60405180910390a25050565b600081116108cd5760405162461bcd60e51b815260040161058790614b2c565b6000546040516305c9ea6360e21b81526101009091046001600160a01b031690631727a98c90610901908690600401614946565b60206040518083038186803b15801561091957600080fd5b505afa15801561092d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061095191906148b5565b61096d5760405162461bcd60e51b815260040161058790614d0e565b60405163667e3f6160e01b81526001600160a01b0384169063667e3f6190610999908590600401614946565b60206040518083038186803b1580156109b157600080fd5b505afa1580156109c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109e991906148b5565b610a055760405162461bcd60e51b815260040161058790614ad9565b610a10338484612924565b610a2c5760405162461bcd60e51b815260040161058790614d7a565b6000610a3661277c565b90506000610a46338686856129c3565b5091505082811015610a6a5760405162461bcd60e51b815260040161058790614a5e565b610a7933868686600087612b65565b610a87848685600086612be8565b610a948584600085612c4d565b336000908152600c6020526040902054610aae9084612c8d565b336000818152600c60205260409081902092909255905183916001600160a01b038716917f1bf72c5c42c48c4dc9c15fe6c006bdaccffcb75f592ff06ab4f54bde7dc23d1f90610b01908a90899061497e565b60405180910390a45050505050565b6001600160a01b03808216600090815260046020526040902054165b919050565b6004602052600090815260409020546001600160a01b031681565b336000908152600460205260409020546001600160a01b039081169082168114801590610b9057506001600160a01b0381166000908152600c602052604090205415155b15610b9e57610b9e81612ccf565b610ba83383612eb3565b5050565b6000610bb661277c565b336000908152600b60205260408120549192509015610be457336000908152600b6020526040902054610c75565b610c756001600060019054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610c3757600080fd5b505afa158015610c4b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c6f91906148e9565b90612c8d565b9050610c828160076128f8565b8211610ca05760405162461bcd60e51b815260040161058790614bfd565b600060019054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b158015610cee57600080fd5b505afa158015610d02573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d2691906148b5565b610d425760405162461bcd60e51b815260040161058790614dee565b610ba8823383612f37565b6001600160a01b0381166000908152600b602052604081205415610d89576001600160a01b0382166000908152600b602052604090205461060c565b61060c6001600060019054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610c3757600080fd5b60066020526000908152604090205463ffffffff1681565b6001546001600160a01b031690565b600080610e0e61277c565b6001600160a01b0384166000908152601160205260408120549192509015610e4e576001600160a01b038416600090815260116020526040902054610ea1565b610ea16001600060019054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610c3757600080fd5b9050610eae8160076128f8565b8211610ebf57600092505050610b2c565b600060019054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b158015610f0d57600080fd5b505afa158015610f21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f4591906148b5565b610f615760405162461bcd60e51b815260040161058790614dee565b610f6c8285836130b5565b949350505050565b600080546040516305c9ea6360e21b8152829182916101009091046001600160a01b031690631727a98c90610fad908890600401614946565b60206040518083038186803b158015610fc557600080fd5b505afa158015610fd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ffd91906148b5565b6110195760405162461bcd60e51b815260040161058790614d0e565b60405163667e3f6160e01b81526001600160a01b0386169063667e3f6190611045908990600401614946565b60206040518083038186803b15801561105d57600080fd5b505afa158015611071573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061109591906148b5565b6110b15760405162461bcd60e51b815260040161058790614ad9565b6110b961277c565b8411156110d85760405162461bcd60e51b815260040161058790614ab4565b6110e3868686613222565b92509250925093509350939050565b6000546040516305c9ea6360e21b81526101009091046001600160a01b031690631727a98c90611126908590600401614946565b60206040518083038186803b15801561113e57600080fd5b505afa158015611152573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061117691906148b5565b6111925760405162461bcd60e51b815260040161058790614d0e565b60405163667e3f6160e01b81526001600160a01b0383169063667e3f61906111be908490600401614946565b60206040518083038186803b1580156111d657600080fd5b505afa1580156111ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061120e91906148b5565b61122a5760405162461bcd60e51b815260040161058790614ad9565b611235338383612924565b6112515760405162461bcd60e51b815260040161058790614d7a565b600061125b61277c565b9050600061126b338585856129c3565b5091505061127e33858584600087612b65565b61128c838583600086612be8565b6112998482600085612c4d565b336000908152600c60205260409020546112b39082612c8d565b336000908152600c6020908152604080832093909355600781528282206001600160a01b038816835281528282208054845181840281018401909552808552929361133e93909283018282801561133357602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611315575b5050505050856133a5565b3360009081526007602090815260408083206001600160a01b038a168452909152902090915061136f9082906133f5565b82846001600160a01b0316336001600160a01b03167f194c3721f48fdddc9ef3098668929b634be03db0fb5eead343224e62a343ba0688604051610b019190614946565b600080546040516305c9ea6360e21b81526101009091046001600160a01b031690631727a98c906113e8908690600401614946565b60206040518083038186803b15801561140057600080fd5b505afa158015611414573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061143891906148b5565b6114545760405162461bcd60e51b815260040161058790614d0e565b61145c61277c565b82111561147b5760405162461bcd60e51b815260040161058790614ab4565b506001600160a01b03919091166000908152601560209081526040808320938352929052205490565b60004382106114c55760405162461bcd60e51b815260040161058790614c26565b6001600160a01b03831660009081526006602052604090205463ffffffff16806114f357600091505061060c565b6001600160a01b038416600090815260056020908152604080832063ffffffff60001986018116855292529091205416831061156f576001600160a01b03841660009081526005602090815260408083206000199490940163ffffffff1683529290522054600160201b90046001600160601b0316905061060c565b6001600160a01b038416600090815260056020908152604080832083805290915290205463ffffffff168310156115aa57600091505061060c565b600060001982015b8163ffffffff168163ffffffff16111561166d57600282820363ffffffff160481036115dc614624565b506001600160a01b038716600090815260056020908152604080832063ffffffff858116855290835292819020815180830190925254928316808252600160201b9093046001600160601b031691810191909152908714156116485760200151945061060c9350505050565b805163ffffffff1687111561165f57819350611666565b6001820392505b50506115b2565b506001600160a01b038516600090815260056020908152604080832063ffffffff909416835292905220546001600160601b03600160201b9091041691505092915050565b6001546001600160a01b031633146116dc5760405162461bcd60e51b815260040161058790614e1d565b60006117168360405180604001604052806016815260200175616d6f756e742065786365656473203936206269747360501b815250613509565b9050811561172d576117288482613538565b6117ab565b6001600160a01b03808516600081815260046020526040902054909116146117675760405162461bcd60e51b815260040161058790614bce565b806001600160601b031661177a8561363c565b6001600160601b031610156117a15760405162461bcd60e51b815260040161058790614dc3565b6117ab84826136cd565b811515846001600160a01b03167fdb9ecd853409c75af997942650919bf9887534c7343059224779461a61220ae4836040516117e79190614eb8565b60405180910390a350505050565b60006117ff61277c565b82111561181e5760405162461bcd60e51b815260040161058790614ab4565b506000908152600d602052604090205490565b600061060c8261363c565b600061060c826137b3565b336000908152600c60205260409020546118735760405162461bcd60e51b815260040161058790614c52565b61187c33612ccf565b565b61188661277c565b8111156118a55760405162461bcd60e51b815260040161058790614ab4565b336000908152600b602052604081205415610be457336000908152600b6020526040902054610c75565b600080546040516305c9ea6360e21b8152829182916101009091046001600160a01b031690631727a98c90611908908990600401614946565b60206040518083038186803b15801561192057600080fd5b505afa158015611934573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061195891906148b5565b6119745760405162461bcd60e51b815260040161058790614d0e565b60405163667e3f6160e01b81526001600160a01b0387169063667e3f61906119a0908890600401614946565b60206040518083038186803b1580156119b857600080fd5b505afa1580156119cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119f091906148b5565b611a0c5760405162461bcd60e51b815260040161058790614ad9565b611a17878787612924565b611a2957508291506000905080611a63565b611a3161277c565b841115611a505760405162461bcd60e51b815260040161058790614ab4565b611a5c878787876129c3565b9250925092505b9450945094915050565b611a7561277c565b811115611a945760405162461bcd60e51b815260040161058790614ab4565b3360009081526011602052604081205415611abe5733600090815260116020526040902054611b11565b611b116001600060019054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610c3757600080fd5b9050611b1e8160076128f8565b8211611b3c5760405162461bcd60e51b815260040161058790614bfd565b600060019054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b158015611b8a57600080fd5b505afa158015611b9e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bc291906148b5565b611bde5760405162461bcd60e51b815260040161058790614dee565b6001546040516376d53d6160e01b81526001600160a01b03909116906376d53d6190611c0e903390600401614946565b60206040518083038186803b158015611c2657600080fd5b505afa158015611c3a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c5e91906148b5565b611c7a5760405162461bcd60e51b815260040161058790614a37565b610ba8823383613825565b60008111611ca55760405162461bcd60e51b815260040161058790614b2c565b6000546040516305c9ea6360e21b81526101009091046001600160a01b031690631727a98c90611cd9903390600401614946565b60206040518083038186803b158015611cf157600080fd5b505afa158015611d05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d2991906148b5565b611d455760405162461bcd60e51b815260040161058790614d0e565b6002546040516323b872dd60e01b81526001600160a01b03909116906323b872dd90611d799033903090869060040161495a565b602060405180830381600087803b158015611d9357600080fd5b505af1158015611da7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dcb91906148b5565b50336000908152601560209081526040808320858452909152902054611df190826128f8565b336000818152601560209081526040808320878452909152908190209290925590518391907fec2480a2fc4a0636b8289155c0665dbbb146d3679c77158fcef551c2424784c990611e43908590614e69565b60405180910390a35050565b60005461010090046001600160a01b031690565b6000611e6d61277c565b831115611e8c5760405162461bcd60e51b815260040161058790614ab4565b6001600160a01b0382166000908152600b602052604081205415611ec8576001600160a01b0383166000908152600b6020526040902054611f1b565b611f1b6001600060019054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610c3757600080fd5b9050611f288160076128f8565b8411611f3857600091505061060c565b600060019054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b158015611f8657600080fd5b505afa158015611f9a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fbe91906148b5565b611fda5760405162461bcd60e51b815260040161058790614dee565b610f6c8484836138ab565b600081116120055760405162461bcd60e51b815260040161058790614b76565b6000546040516305c9ea6360e21b81526101009091046001600160a01b031690631727a98c90612039908690600401614946565b60206040518083038186803b15801561205157600080fd5b505afa158015612065573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061208991906148b5565b6120a55760405162461bcd60e51b815260040161058790614d0e565b826001600160a01b031663d46d17ca6040518163ffffffff1660e01b815260040160206040518083038186803b1580156120de57600080fd5b505afa1580156120f2573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061211691906148e9565b6064036121355760405162461bcd60e51b815260040161058790614e47565b60405163667e3f6160e01b81526001600160a01b0384169063667e3f6190612161908590600401614946565b60206040518083038186803b15801561217957600080fd5b505afa15801561218d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121b191906148b5565b6121cd5760405162461bcd60e51b815260040161058790614ad9565b6001546040516376d53d6160e01b81526001600160a01b03909116906376d53d61906121fd908590600401614946565b60206040518083038186803b15801561221557600080fd5b505afa158015612229573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061224d91906148b5565b6122695760405162461bcd60e51b815260040161058790614a37565b3360009081526007602090815260408083206001600160a01b0387168452909152902054600a116122ac5760405162461bcd60e51b815260040161058790614cc7565b806122b63361363c565b6001600160601b031610156122dd5760405162461bcd60e51b815260040161058790614a5e565b6122e8338484612924565b612337573360009081526007602090815260408083206001600160a01b0387811685529083529083208054600181018255908452919092200180546001600160a01b0319169184169190911790555b600061234161277c565b905061235233858585600186612b65565b612360838584600185612be8565b61236d8483600184612c4d565b336000908152600c602052604090205461238790836128f8565b336000818152600c60205260409081902092909255905182916001600160a01b038616917ffac22e5ca1ad9c0e062e405d23fa971f266026b08a9339450a055b848ba742a1906123da908990889061497e565b60405180910390a450505050565b6000806123f361277c565b6001600160a01b0384166000908152600b60205260408120549192509015612433576001600160a01b0384166000908152600b6020526040902054612486565b6124866001600060019054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610c3757600080fd5b90506124938160076128f8565b82116124a457600092505050610b2c565b600060019054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b1580156124f257600080fd5b505afa158015612506573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061252a91906148b5565b6125465760405162461bcd60e51b815260040161058790614dee565b610f6c8285836138ab565b600560209081526000928352604080842090915290825290205463ffffffff811690600160201b90046001600160601b031682565b600061259061277c565b336000908152601160205260408120549192509015611abe5733600090815260116020526040902054611b11565b6001600160a01b03811660009081526011602052604081205415610d89576001600160a01b03821660009081526011602052604090205461060c565b600061260461277c565b8311156126235760405162461bcd60e51b815260040161058790614ab4565b6001600160a01b0382166000908152601160205260408120541561265f576001600160a01b0383166000908152601160205260409020546126b2565b6126b26001600060019054906101000a90046001600160a01b03166001600160a01b031663ff4dfa516040518163ffffffff1660e01b815260040160206040518083038186803b158015610c3757600080fd5b90506126bf8160076128f8565b84116126cf57600091505061060c565b600060019054906101000a90046001600160a01b03166001600160a01b031663782536046040518163ffffffff1660e01b815260040160206040518083038186803b15801561271d57600080fd5b505afa158015612731573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061275591906148b5565b6127715760405162461bcd60e51b815260040161058790614dee565b610f6c8484836130b5565b600061279660016127904262015180613ab2565b906128f8565b905090565b6001600160a01b03821660009081526012602090815260408083208054825181850281018501909352808352849384936060939092909183018282801561280157602002820191906000526020600020905b8154815260200190600101908083116127ed575b5050506001600160a01b0389166000908152601360209081526040918290208054835181840281018401909452808452959650606095929450925083018282801561286b57602002820191906000526020600020905b815481526020019060010190808311612857575b5050506001600160a01b038a16600090815260146020908152604091829020805483518184028101840190945280845295965060609592945092508301828280156128d557602002820191906000526020600020905b8154815260200190600101908083116128c1575b505050505090506128e88383838a613af4565b9550955095505050509250925092565b60008282018381101561291d5760405162461bcd60e51b815260040161058790614b97565b9392505050565b6000805b6001600160a01b038086166000908152600760209081526040808320938816835292905220548110156129b8576001600160a01b038581166000908152600760209081526040808320888516845290915290208054918516918390811061298b57fe5b6000918252602090912001546001600160a01b031614156129b057600191505061291d565b600101612928565b506000949350505050565b6001600160a01b03808516600090815260086020908152604080832087851684528252808320938616835292815282822080548451818402810184019095528085529293849384936060939190830182828015612a3f57602002820191906000526020600020905b815481526020019060010190808311612a2b575b5050506001600160a01b03808c1660009081526009602090815260408083208e851684528252808320938d1683529281529082902080548351818402810184019094528084529596506060959294509250830182828015612abf57602002820191906000526020600020905b815481526020019060010190808311612aab575b5050506001600160a01b03808d166000908152600a602090815260408083208f851684528252808320938e1683529281529082902080548351818402810184019094528084529596506060959294509250830182828015612b3f57602002820191906000526020600020905b815481526020019060010190808311612b2b575b50505050509050612b528383838a613af4565b9550955095505050509450945094915050565b6001600160a01b0380871660008181526008602090815260408083208a8616808552908352818420958a168085529583528184208585526009845282852082865284528285208786528452828520958552600a8452828520918552908352818420958452949091529020612bdd838383898989613c04565b505050505050505050565b6001600160a01b038086166000818152600e60209081526040808320948916808452948252808320848452600f8352818420868552835281842094845260108352818420958452949091529020612c43838383898989613c04565b5050505050505050565b6001600160a01b03841660009081526012602090815260408083206013835281842060149093529220612c84838383898989613c04565b50505050505050565b600061291d83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250613eb1565b6000612cd961277c565b90506060600060019054906101000a90046001600160a01b03166001600160a01b031663c251b5656040518163ffffffff1660e01b815260040160006040518083038186803b158015612d2b57600080fd5b505afa158015612d3f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052612d67919081019061480a565b905060005b8151811015612ead576000828281518110612d8357fe5b6020908102919091018101516001600160a01b0380881660009081526007845260408082209284168252918452819020805482518186028101860190935280835292945060609391929091830182828015612e0757602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311612de9575b5050505050905060005b8151811015612ea2576000828281518110612e2857fe5b602002602001015190506000612e408986848b6129c3565b50915050612e533386848460008d612b65565b612e6182868360008c612be8565b612e6e858260008b612c4d565b336000908152600c6020526040902054612e889082612c8d565b336000908152600c60205260409020555050600101612e11565b505050600101612d6c565b50505050565b6001600160a01b03808316600081815260046020818152604080842080546003845282862054949093528787166001600160a01b031984168117909155905191909516946001600160601b039092169391928592917f3134e8a2e6d97e929a7e54011ea5485d7d196dd5f0ba4d4ef95803e8e3fc257f9190a4612ead828483613edd565b6000612f448484846138ab565b905060008111612f665760405162461bcd60e51b815260040161058790614cea565b612f71846007612c8d565b6001600160a01b038085166000908152600b60205260409081902092909255600254600154925163095ea7b360e01b81529082169263095ea7b392612fbd92911690859060040161497e565b602060405180830381600087803b158015612fd757600080fd5b505af1158015612feb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061300f91906148b5565b506001546040516330d6a97560e01b81526001600160a01b03909116906330d6a97590613042908690859060040161497e565b600060405180830381600087803b15801561305c57600080fd5b505af1158015613070573d6000803e3d6000fd5b5050505061307c61277c565b836001600160a01b03167f987d620f307ff6b94d58743cb7a7509f24071586a77759b77c2d4e29f75a2f9a836040516117e79190614e69565b600080806130c48460016128f8565b90505b6130d2866007612c8d565b8111613219576060600060019054906101000a90046001600160a01b03166001600160a01b031663c251b5656040518163ffffffff1660e01b815260040160006040518083038186803b15801561312857600080fd5b505afa15801561313c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052613164919081019061480a565b905060005b815181101561320f57600082828151811061318057fe5b602002602001015190506000613196828661279b565b92505050806131a6575050613207565b60006131b38a8488613222565b6001600160a01b03861660009081526015602090815260408083208c845290915281205491945090925090506131f3846131ed84866140a3565b90613ab2565b90506131ff89826128f8565b985050505050505b600101613169565b50506001016130c7565b50949350505050565b6001600160a01b038084166000908152600e6020908152604080832093861683529281528282208054845181840281018401909552808552929384938493606093919083018282801561329457602002820191906000526020600020905b815481526020019060010190808311613280575b5050506001600160a01b03808b166000908152600f60209081526040808320938d168352928152908290208054835181840281018401909452808452959650606095929450925083018282801561330a57602002820191906000526020600020905b8154815260200190600101908083116132f6575b5050506001600160a01b03808c166000908152601060209081526040808320938e168352928152908290208054835181840281018401909452808452959650606095929450925083018282801561338057602002820191906000526020600020905b81548152602001906001019080831161336c575b505050505090506133938383838a613af4565b95509550955050505093509350939050565b60008060005b84518110156133ed57836001600160a01b03168582815181106133ca57fe5b60200260200101516001600160a01b031614156133e5578091505b6001016133ab565b509392505050565b8054613402906001612c8d565b82141561343a578080548061341357fe5b600082815260209020810160001990810180546001600160a01b0319169055019055610ba8565b80548190613449906001612c8d565b8154811061345357fe5b9060005260206000200160009054906101000a90046001600160a01b031681838154811061347d57fe5b600091825260209091200180546001600160a01b0319166001600160a01b0392909216919091179055805481906134b5906001612c8d565b815481106134bf57fe5b600091825260209091200180546001600160a01b031916905580548190806134e357fe5b600082815260209020810160001990810180546001600160a01b03191690550190555050565b600081600160601b84106135305760405162461bcd60e51b815260040161058791906149e4565b509192915050565b6001600160a01b03821661355e5760405162461bcd60e51b815260040161058790614d9d565b6001600160a01b0382166000908152600360209081526040918290205482518084019093526015835274766f746520616d6f756e74206f766572666c6f777360581b918301919091526135be916001600160601b039091169083906140dd565b6001600160a01b038316600090815260036020526040902080546bffffffffffffffffffffffff19166001600160601b03929092169190911790556136038282614110565b816001600160a01b03167fbb104626c67690cd9023bde19b0804077126d78eb9bc3eb35de512eda655a311826040516108a19190614eb8565b600080613648836137b3565b90506001600160601b038116156136c4576136bd600c6000856001600160a01b03166001600160a01b03168152602001908152602001600020546040518060400160405280601d81526020017f766f746572566f7465734f757420657863656564732039362062697473000000815250613509565b810361291d565b60009392505050565b6001600160a01b038216600090815260036020908152604091829020548251808401909352601b83527f766f746520616d6f756e7420657863656564732062616c616e6365000000000091830191909152613735916001600160601b03909116908390614182565b6001600160a01b038316600090815260036020526040902080546bffffffffffffffffffffffff19166001600160601b039290921691909117905561377a82826141b9565b816001600160a01b03167f40b10d9892192657ad11f6c742381c432b492799468ace10b6ffb5842e34b024826040516108a19190614eb8565b6001600160a01b03811660009081526006602052604081205463ffffffff16806137de57600061291d565b6001600160a01b038316600090815260056020908152604080832063ffffffff60001986011684529091529020546001600160601b03600160201b90910416915050919050565b60006138328484846130b5565b9050600081116138545760405162461bcd60e51b815260040161058790614cea565b61385f846007612c8d565b6001600160a01b038085166000908152601160205260409081902092909255600254600154925163095ea7b360e01b81529082169263095ea7b392612fbd92911690859060040161497e565b600080806138ba8460016128f8565b90505b6138c8866007612c8d565b8111613219576060600060019054906101000a90046001600160a01b03166001600160a01b031663c251b5656040518163ffffffff1660e01b815260040160006040518083038186803b15801561391e57600080fd5b505afa158015613932573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261395a919081019061480a565b905060005b8151811015613aa857600082828151811061397657fe5b60200260200101519050600061398c828661279b565b925050508061399c575050613aa0565b6001600160a01b03808a166000908152600760209081526040808320938616835292815290829020805483518184028101840190945280845260609392830182828015613a1257602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116139f4575b50505050509050600080600090505b8251811015613a6c576000838281518110613a3857fe5b602002602001015190506000613a508e88848d6129c3565b9250613a609150859050826128f8565b93505050600101613a21565b506000878152600d602052604081205490613a8b856131ed84866140a3565b9050613a978a826128f8565b99505050505050505b60010161395f565b50506001016138bd565b600061291d83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506141e3565b83516000908190819080613b12578460008093509350935050611a63565b87600081518110613b1f57fe5b6020026020010151851015613b3e578460008093509350935050611a63565b6000613b4b826001612c8d565b90506000898281518110613b5b57fe5b6020026020010151905080871415613ba45786898381518110613b7a57fe5b6020026020010151898481518110613b8e57fe5b6020026020010151955095509550505050611a63565b80871115613bf85786898381518110613bb957fe5b6020026020010151613bea620151808c8681518110613bd457fe5b60200260200101516140a390919063ffffffff16565b955095509550505050611a63565b612b528a8a8a8a61421a565b855462015180428190066000613c1a8383612c8d565b905083613c95578515613c7857895460018181018c5560008c815260208082209093018890558b549182018c558b8152919091200187905587613c5d88836140a3565b81546001810183556000928352602090922090910155613c90565b60405162461bcd60e51b815260040161058790614c9b565b613ea5565b6000613ca2856001612c8d565b905060008b8281548110613cb257fe5b9060005260206000200154905060008b8381548110613ccd57fe5b9060005260206000200154905060008b8481548110613ce857fe5b906000526020600020015490506000808a851415613da9578b15613d2d57613d10848e6128f8565b9150613d26613d1f8e896140a3565b84906128f8565b9050613d70565b8c841015613d4d5760405162461bcd60e51b815260040161058790614a88565b613d57848e612c8d565b9150613d6d613d668e896140a3565b8490612c8d565b90505b818f8781548110613d7d57fe5b9060005260206000200181905550808e8781548110613d9857fe5b600091825260209091200155613e9e565b8b15613ddc57613db9848e6128f8565b9150613dd5613dc88e896140a3565b61279086620151806140a3565b9050613e25565b8c841015613dfc5760405162461bcd60e51b815260040161058790614b4a565b613e06848e612c8d565b9150613e22613e158e896140a3565b610c6f86620151806140a3565b90505b8f8b90806001815401808255809150506001900390600052602060002001600090919091909150558e8290806001815401808255809150506001900390600052602060002001600090919091909150558d8190806001815401808255809150506001900390600052602060002001600090919091909150555b5050505050505b50505050505050505050565b60008184841115613ed55760405162461bcd60e51b815260040161058791906149e4565b505050900390565b816001600160a01b0316836001600160a01b031614158015613f0857506000816001600160601b0316115b1561409e576001600160a01b03831615613fd6576001600160a01b03831660009081526006602052604081205463ffffffff169081613f48576000613f87565b6001600160a01b0385166000908152600560209081526040808320600019860163ffffffff168452909152902054600160201b90046001600160601b03165b90506000613fc4828560405180604001604052806016815260200175766f746520616d6f756e7420756e646572666c6f777360501b815250614182565b9050613fd28684848461442b565b5050505b6001600160a01b0382161561409e576001600160a01b03821660009081526006602052604081205463ffffffff169081614011576000614050565b6001600160a01b0384166000908152600560209081526040808320600019860163ffffffff168452909152902054600160201b90046001600160601b03165b9050600061408c828560405180604001604052806015815260200174766f746520616d6f756e74206f766572666c6f777360581b8152506140dd565b905061409a8584848461442b565b5050505b505050565b6000826140b25750600061060c565b828202828482816140bf57fe5b041461291d5760405162461bcd60e51b815260040161058790614d39565b6000838301826001600160601b0380871690831610156132195760405162461bcd60e51b815260040161058791906149e4565b6001600160a01b0382811660009081526004602052604090205416614159576001600160a01b038216600081815260046020526040902080546001600160a01b03191690911790555b6001600160a01b038083166000908152600460205260408120549091169061409e908284613edd565b6000836001600160601b0316836001600160601b031611158290613ed55760405162461bcd60e51b815260040161058791906149e4565b6001600160a01b038083166000908152600460205260408120549091169061409e90829084613edd565b600081836142045760405162461bcd60e51b815260040161058791906149e4565b50600083858161421057fe5b0495945050505050565b60008060008060009050600061423b60018a51612c8d90919063ffffffff16565b9050600061424e60026131ed84866128f8565b90505b818310156143f257868a828151811061426657fe5b60200260200101511415614295578689828151811061428157fe5b6020026020010151898381518110613b8e57fe5b868a82815181106142a257fe5b6020026020010151111561434f576000811180156142dc5750868a6142c8836001612c8d565b815181106142d257fe5b6020026020010151105b156143265786896142ee836001612c8d565b815181106142f857fe5b6020026020010151613bea620151808c61431c600187612c8d90919063ffffffff16565b81518110613bd457fe5b8061433d5786600080955095509550505050611a63565b614348816001612c8d565b91506143dc565b868a828151811061435c57fe5b602002602001015110156143dc578951614377906001612c8d565b811080156143a15750868a61438d8360016128f8565b8151811061439757fe5b6020026020010151115b156143ce57868982815181106143b357fe5b6020026020010151613bea620151808c8581518110613bd457fe5b6143d98160016128f8565b92505b6143eb60026131ed84866128f8565b9050614251565b868a82815181106143ff57fe5b60200260200101511461441e5786600080955095509550505050611a63565b8689828151811061428157fe5b600061446c436040518060400160405280601c81526020017f626c6f636b206e756d62657220657863656564732033322062697473000000008152506145fd565b905060008463ffffffff161180156144b557506001600160a01b038516600090815260056020908152604080832063ffffffff6000198901811685529252909120548282169116145b15614514576001600160a01b0385166000908152600560209081526040808320600019880163ffffffff168452909152902080546fffffffffffffffffffffffff000000001916600160201b6001600160601b038516021790556145b3565b60408051808201825263ffffffff80841682526001600160601b0380861660208085019182526001600160a01b038b166000818152600583528781208c871682528352878120965187549451909516600160201b026fffffffffffffffffffffffff000000001995871663ffffffff19958616179590951694909417909555938252600690935292909220805460018801909316929091169190911790555b846001600160a01b03167fdec2bacdd2f05b59de34da9b523dff8be42e5e38e818c82fdb0bae774387a72484846040516145ee929190614ecc565b60405180910390a25050505050565b600081600160201b84106135305760405162461bcd60e51b815260040161058791906149e4565b604080518082019091526000808252602082015290565b805161060c81614f0d565b600060208284031215614657578081fd5b813561291d81614f0d565b60008060408385031215614674578081fd5b823561467f81614f0d565b9150602083013561468f81614f0d565b809150509250929050565b6000806000606084860312156146ae578081fd5b83356146b981614f0d565b925060208401356146c981614f0d565b915060408401356146d981614f0d565b809150509250925092565b600080600080608085870312156146f9578081fd5b843561470481614f0d565b9350602085013561471481614f0d565b9250604085013561472481614f0d565b9396929550929360600135925050565b600080600060608486031215614748578283fd5b833561475381614f0d565b9250602084013561476381614f0d565b929592945050506040919091013590565b60008060408385031215614786578182fd5b823561479181614f0d565b946020939093013593505050565b6000806000606084860312156147b3578283fd5b83356147be81614f0d565b92506020840135915060408401356146d981614f25565b600080604083850312156147e7578182fd5b82356147f281614f0d565b9150602083013563ffffffff8116811461468f578182fd5b6000602080838503121561481c578182fd5b825167ffffffffffffffff80821115614833578384fd5b818501915085601f830112614846578384fd5b815181811115614854578485fd5b8381029150614864848301614ee6565b8181528481019084860184860187018a101561487e578788fd5b8795505b838610156148a8576148948a8261463b565b835260019590950194918601918601614882565b5098975050505050505050565b6000602082840312156148c6578081fd5b815161291d81614f25565b6000602082840312156148e2578081fd5b5035919050565b6000602082840312156148fa578081fd5b5051919050565b60008060408385031215614913578182fd5b82359150602083013561468f81614f0d565b60008060408385031215614937578182fd5b50508035926020909101359150565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b6020808252825182820181905260009190848201906040850190845b818110156149d85783516001600160a01b0316835292840192918401916001016149b3565b50909695505050505050565b6000602080835283518082850152825b81811015614a10578581018301518582016040015282016149f4565b81811115614a215783604083870101525b50601f01601f1916929092016040019392505050565b6020808252600d908201526c1b9bdd081b5a5b881b5a5b9959609a1b604082015260600190565b60208082526010908201526f6e6f7420656e6f75676820766f74657360801b604082015260600190565b602080825260129082015271323a206e6f7420656e6f756768206d696e6560701b604082015260600190565b6020808252600b908201526a696e76616c69642064617960a81b604082015260600190565b6020808252600f908201526e696e76616c6964207365727669636560881b604082015260600190565b60208082526010908201526f3737ba1039b121b7b73a3937b63632b960811b604082015260600190565b6020808252600490820152637a65726f60e01b604082015260600190565b602080825260129082015271333a206e6f7420656e6f756768206d696e6560701b604082015260600190565b602080825260079082015266313a207a65726f60c81b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526015908201527436bab9ba103232b632b3b0ba32903a379039b2b63360591b604082015260600190565b6020808252600f908201526e185b1c9958591e4818db185a5b5959608a1b604082015260600190565b6020808252601290820152711b9bdd081e595d0819195d195c9b5a5b995960721b604082015260600190565b6020808252600c908201526b1b9bc81d9bdd195cc81bdd5d60a21b604082015260600190565b602080825260099082015268696e697420646f6e6560b81b604082015260600190565b602080825260129082015271313a206e6f7420656e6f756768206d696e6560701b604082015260600190565b6020808252600990820152681b1a5b5a5d081b595d60ba1b604082015260600190565b6020808252600a90820152696e6f207265776172647360b01b604082015260600190565b602080825260119082015270696e76616c696420636f6d6d756e69747960781b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b6020808252600990820152681b9bdd08199bdd5b9960ba1b604082015260600190565b6020808252600c908201526b7a65726f206164647265737360a01b604082015260600190565b6020808252601190820152706d75737420726563616c6c20766f74657360781b604082015260600190565b6020808252601590820152741b995959081c995dd85c991cc81c995b19585cd959605a1b604082015260600190565b60208082526010908201526f1b9bdd081cd894dd1c9bdb99d41bdbdb60821b604082015260600190565b602080825260089082015267191d103d32b9379760c11b604082015260600190565b90815260200190565b9283526020830191909152604082015260600190565b63ffffffff91909116815260200190565b63ffffffff9290921682526001600160601b0316602082015260400190565b6001600160601b0391909116815260200190565b6001600160601b0392831681529116602082015260400190565b60405181810167ffffffffffffffff81118282101715614f0557600080fd5b604052919050565b6001600160a01b0381168114614f2257600080fd5b50565b8015158114614f2257600080fdfea26469706673582212207a8bcc405dce1dde5e2ede788dc579bc014ae4380485cf7f02e917efcb8fbdfc64736f6c634300060c0033
[ 0, 16, 9, 12, 10, 5 ]
0x4b63ce7e179d1db5ddac5d9d54e48356cf3e8b7d
pragma solidity 0.5.17; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } //转账 function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ // function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract AIB2020 is Context, ERC20, ERC20Detailed { //Zhang0PeterCoin: 代币的全名 //ZPC:代币的简写 //3: 代币小数点位数,代币的最小单位, 3表示我们可以拥有 0.001单位个代币 constructor () public ERC20Detailed("AIB on ERC20 V1", "AIB", 8) { //初始化币,并把所有的币都给部署智能合约的ETH钱包地址 //233:代币的总数量 _mint(_msgSender(), 21000000 * (10 ** uint256(decimals()))); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063395093511161007157806339509351146101d957806370a082311461020557806395d89b411461022b578063a457c2d714610233578063a9059cbb1461025f578063dd62ed3e1461028b576100a9565b806306fdde03146100ae578063095ea7b31461012b57806318160ddd1461016b57806323b872dd14610185578063313ce567146101bb575b600080fd5b6100b66102b9565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f05781810151838201526020016100d8565b50505050905090810190601f16801561011d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101576004803603604081101561014157600080fd5b506001600160a01b03813516906020013561034f565b604080519115158252519081900360200190f35b61017361036c565b60408051918252519081900360200190f35b6101576004803603606081101561019b57600080fd5b506001600160a01b03813581169160208101359091169060400135610372565b6101c36103ff565b6040805160ff9092168252519081900360200190f35b610157600480360360408110156101ef57600080fd5b506001600160a01b038135169060200135610408565b6101736004803603602081101561021b57600080fd5b50356001600160a01b031661045c565b6100b6610477565b6101576004803603604081101561024957600080fd5b506001600160a01b0381351690602001356104d8565b6101576004803603604081101561027557600080fd5b506001600160a01b038135169060200135610546565b610173600480360360408110156102a157600080fd5b506001600160a01b038135811691602001351661055a565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b820191906000526020600020905b81548152906001019060200180831161032857829003601f168201915b5050505050905090565b600061036361035c610585565b8484610589565b50600192915050565b60025490565b600061037f848484610675565b6103f58461038b610585565b6103f085604051806060016040528060288152602001610935602891396001600160a01b038a166000908152600160205260408120906103c9610585565b6001600160a01b03168152602081019190915260400160002054919063ffffffff6107d116565b610589565b5060019392505050565b60055460ff1690565b6000610363610415610585565b846103f08560016000610426610585565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff61086816565b6001600160a01b031660009081526020819052604090205490565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156103455780601f1061031a57610100808354040283529160200191610345565b60006103636104e5610585565b846103f0856040518060600160405280602581526020016109a6602591396001600061050f610585565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff6107d116565b6000610363610553610585565b8484610675565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b3390565b6001600160a01b0383166105ce5760405162461bcd60e51b81526004018080602001828103825260248152602001806109826024913960400191505060405180910390fd5b6001600160a01b0382166106135760405162461bcd60e51b81526004018080602001828103825260228152602001806108ed6022913960400191505060405180910390fd5b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166106ba5760405162461bcd60e51b815260040180806020018281038252602581526020018061095d6025913960400191505060405180910390fd5b6001600160a01b0382166106ff5760405162461bcd60e51b81526004018080602001828103825260238152602001806108ca6023913960400191505060405180910390fd5b6107428160405180606001604052806026815260200161090f602691396001600160a01b038616600090815260208190526040902054919063ffffffff6107d116565b6001600160a01b038085166000908152602081905260408082209390935590841681522054610777908263ffffffff61086816565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156108605760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561082557818101518382015260200161080d565b50505050905090810190601f1680156108525780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6000828201838110156108c2576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b939250505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a723158200d1d7faa6754d74b7a40e0489566283646cecb89c0c24a0a887d31b108d4a23064736f6c63430005110032
[ 38 ]
0x4b683854959579df565cbf13ee0f2807dc3eba3f
pragma solidity 0.6.6; 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. * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract 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(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is IERC20, Ownable { 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 {totalSupply} {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 () public { _name = 'Yfve.Finance'; _symbol = 'YFVE'; _decimals = 18; _mint(msg.sender, 40000000000000000000000); } /** * @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(msg.sender, 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(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`. */ 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 Destroys `amount` tokens from `account`, reducing the total supply */ function burn(uint256 _amount) public onlyOwner { _burn(msg.sender, _amount); } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
0x608060405234801561001057600080fd5b50600436106100f55760003560e01c806370a0823111610097578063a457c2d711610066578063a457c2d7146102ca578063a9059cbb146102f6578063dd62ed3e14610322578063f2fde38b14610350576100f5565b806370a0823114610270578063715018a6146102965780638da5cb5b1461029e57806395d89b41146102c2576100f5565b806323b872dd116100d357806323b872dd146101d1578063313ce56714610207578063395093511461022557806342966c6814610251576100f5565b806306fdde03146100fa578063095ea7b31461017757806318160ddd146101b7575b600080fd5b610102610376565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561013c578181015183820152602001610124565b50505050905090810190601f1680156101695780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101a36004803603604081101561018d57600080fd5b506001600160a01b03813516906020013561040c565b604080519115158252519081900360200190f35b6101bf610422565b60408051918252519081900360200190f35b6101a3600480360360608110156101e757600080fd5b506001600160a01b03813581169160208101359091169060400135610428565b61020f610497565b6040805160ff9092168252519081900360200190f35b6101a36004803603604081101561023b57600080fd5b506001600160a01b0381351690602001356104a0565b61026e6004803603602081101561026757600080fd5b50356104dc565b005b6101bf6004803603602081101561028657600080fd5b50356001600160a01b0316610548565b61026e610563565b6102a661060c565b604080516001600160a01b039092168252519081900360200190f35b61010261061b565b6101a3600480360360408110156102e057600080fd5b506001600160a01b03813516906020013561067c565b6101a36004803603604081101561030c57600080fd5b506001600160a01b0381351690602001356106d1565b6101bf6004803603604081101561033857600080fd5b506001600160a01b03813581169160200135166106de565b61026e6004803603602081101561036657600080fd5b50356001600160a01b0316610709565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104025780601f106103d757610100808354040283529160200191610402565b820191906000526020600020905b8154815290600101906020018083116103e557829003601f168201915b5050505050905090565b6000610419338484610808565b50600192915050565b60035490565b60006104358484846108f4565b61048d843361048885604051806060016040528060288152602001610d58602891396001600160a01b038a166000908152600260209081526040808320338452909152902054919063ffffffff610a5d16565b610808565b5060019392505050565b60065460ff1690565b3360008181526002602090815260408083206001600160a01b03871684529091528120549091610419918590610488908663ffffffff610af416565b6000546001600160a01b0316331461053b576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6105453382610b55565b50565b6001600160a01b031660009081526001602052604090205490565b6000546001600160a01b031633146105c2576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031690565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156104025780601f106103d757610100808354040283529160200191610402565b6000610419338461048885604051806060016040528060258152602001610dea602591393360009081526002602090815260408083206001600160a01b038d168452909152902054919063ffffffff610a5d16565b60006104193384846108f4565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b6000546001600160a01b03163314610768576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b0381166107ad5760405162461bcd60e51b8152600401808060200182810382526026815260200180610cea6026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03831661084d5760405162461bcd60e51b8152600401808060200182810382526024815260200180610dc66024913960400191505060405180910390fd5b6001600160a01b0382166108925760405162461bcd60e51b8152600401808060200182810382526022815260200180610d106022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166109395760405162461bcd60e51b8152600401808060200182810382526025815260200180610da16025913960400191505060405180910390fd5b6001600160a01b03821661097e5760405162461bcd60e51b8152600401808060200182810382526023815260200180610ca56023913960400191505060405180910390fd5b610989838383610c5d565b6109cc81604051806060016040528060268152602001610d32602691396001600160a01b038616600090815260016020526040902054919063ffffffff610a5d16565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610a01908263ffffffff610af416565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610aec5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610ab1578181015183820152602001610a99565b50505050905090810190601f168015610ade5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082820183811015610b4e576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6001600160a01b038216610b9a5760405162461bcd60e51b8152600401808060200182810382526021815260200180610d806021913960400191505060405180910390fd5b610ba682600083610c5d565b610be981604051806060016040528060228152602001610cc8602291396001600160a01b038516600090815260016020526040902054919063ffffffff610a5d16565b6001600160a01b038316600090815260016020526040902055600354610c15908263ffffffff610c6216565b6003556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b505050565b6000610b4e83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610a5d56fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e63654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220665fc74367b4a5d2f475beebb0c6444d2df2e0195ae452865f7d81ba3e48f62764736f6c63430006060033
[ 38 ]
0x4bc7746f37be8a5e2fe10f8162fcbfce2d912e84
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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"); } } library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } contract Decryption { function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } 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)); } } library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - (subtracted.a), p); } else { difference.a = p - (addmod(subtracted.a, p - (diminished.a), p)); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - (subtracted.b), p); } else { difference.b = p - (addmod(subtracted.b, p - (diminished.b), p)); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = p - addmod(t2, p - t0, p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = p - mulmod(value.b, t3, p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG1() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = p - sum.y.a; sum.y.b = p - sum.y.b; } function toUS(G2Point memory value) internal pure returns (G2Point memory) { return G2Point({ x: value.x.mulFp2(Fp2Operations.Fp2Point({ a: 1, b: 0 }).squaredFp2()), y: value.y.mulFp2( Fp2Operations.Fp2Point({ a: 1, b: 0 }).mulFp2(Fp2Operations.Fp2Point({ a: 1, b: 0 }).squaredFp2()) ) }); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = p - result.y.a; result.y.b = p - result.y.b; } } function mulG2( G2Point memory value, uint scalar ) internal view returns (G2Point memory result) { uint step = scalar; result = G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); G2Point memory tmp = value; uint gs = gasleft(); while (step > 0) { if (step % 2 == 1) { result = addG2(result, tmp); } gs = gasleft(); tmp = doubleG2(tmp); step >>= 1; } } } library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } interface ILocker { /** * @dev Returns the locked amount of untransferable tokens of a given `wallet` */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns the locked amount of untransferable and un-delegatable tokens of a given `wallet`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } interface ISkaleDKG { function openChannel(bytes32 schainId) external; function deleteChannel(bytes32 schainId) external; function isLastDKGSuccesful(bytes32 groupIndex) external view returns (bool); function isChannelOpened(bytes32 schainId) external view returns (bool); } 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; } library MathUtils { event UnderflowError( uint a, uint b ); uint constant private _EPS = 1e6; function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Can't reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint newValue = sequence.value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value != newValue) { sequence.value = newValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint _i = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len.sub(1); while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; uint constant private _FICTIOUS_MONTH_START = 1599523200; uint constant private _FICTIOUS_MONTH_NUMBER = 9; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); if (timestamp >= _FICTIOUS_MONTH_START) { month = month.add(1); } return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; if (_month > _FICTIOUS_MONTH_NUMBER) { _month = _month.sub(1); } else if (_month == _FICTIOUS_MONTH_NUMBER) { return _FICTIOUS_MONTH_START; } year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * Adds actual contract to mapping of actual contract addresses * @param contractsName - contracts name in skale manager system * @param newContractsAddress - contracts address in skale manager system */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract * @param contractName - human readable name of contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName3))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No any changes on nodes"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } contract Punisher is Permissions, ILocker { /** * @dev Emitted when a slashing condition occurs. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted when a forgive condition occurs. */ event Forgive( address wallet, uint amount ); // holder => tokens mapping (address => uint) private _locked; /** * @dev Executes slashing on a validator and its delegations by an `amount` * of tokens. Currently, SkaleDKG is the only service allowed to execute * slashing. * * Emits a Slash event. * * @param validatorId uint validator to be slashed * @param amount uint slashed amount */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Owner to forgive a slashing condition. * * Emits a Forgive event. * * @param holder address of the slashed * @param amount uint amount to be forgiven */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See ILocker-getAndUpdateLockedAmount */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker-getAndUpdateForbiddenForDelegationAmount */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } // informs that Schain is created event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); event SchainDeleted( address owner, string name, bytes32 indexed schainId ); event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); event NodeAdded( bytes32 schainId, uint newNode ); // informs that Schain based on some Nodes event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param data - Schain's data */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schian"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev deleteSchain - removes Schain from the system * function could be run only by executor * @param from - owner of Schain * @param name - Schain name */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not an owner of Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, nodesInGroup[i])) { schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); _addSpace(nodesInGroup[i], partOfNode); continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { _addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, nodesInGroup[i])) { schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); _addSpace(nodesInGroup[i], partOfNode); continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); _addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccesful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No any free Nodes for rotation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev verifySignature - verify signature which create Group by Groups BLS master public key * @param signatureA - first part of BLS signature * @param signatureB - second part of BLS signature * @param hash - hashed message * @param counter - smallest sub from square * @param hashA - first part of hashed message * @param hashB - second part of hashed message * @param schainName - name of the Schain * @return true - if correct, false - if not */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev getSchainPrice - returns current price for given Schain * @param typeOfSchain - type of Schain * @param lifetime - lifetime of Schain * @return current price for given Schain */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev getNodesDataFromTypeOfSchain - returns number if Nodes * and part of Node which needed to this Schain * @param typeOfSchain - type of Schain * @return numberOfNodes - number of Nodes needed to this Schain * @return partOfNode - divisor of given type of Schain */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { revert("Bad schain type"); } } function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev fallbackSchainParameterDataConverter - converts data from bytes to normal parameters * @param data - concatenated parameters * @return schainParameters Parsed lifetime, typeOfSchain, nonce and name */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev _addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function _addSpace(uint nodeIndex, uint8 partOfNode) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev _createGroupForSchain - creates Group for Schain * @param schainName - name of Schain * @param schainId - hash by name of Schain * @param numberOfNodes - number of Nodes needed for this Schain * @param partOfNode - divisor of given type of Schain */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev _addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param schainParameters - Schain's data */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; /** * @dev initializeSchain - initializes Schain * function could be run only by executor * @param name - SChain name * @param from - Schain owner * @param lifetime - initial lifetime of Schain * @param deposit - given amount of SKL */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); } function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev setSchainIndex - adds Schain's hash to owner * function could be run only by executor * @param schainId - hash by Schain name * @param from - Schain owner */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev changeLifetime - changes Lifetime for Schain * function could be run only by executor * @param schainId - hash by Schain name * @param lifetime - time which would be added to lifetime of Schain * @param deposit - amount of SKL which payed for this time */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev removeSchain - removes Schain from the system * function could be run only by executor * @param schainId - hash by Schain name * @param from - owner of Schain */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainId = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainId); } function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev deleteGroup - delete Group from Data contract * function could be run only by executor * @param schainId - Groups identifier */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; if (skaleDKG.isChannelOpened(schainId)) { skaleDKG.deleteChannel(schainId); } } /** * @dev setException - sets a Node like exception * function could be run only by executor * @param schainId - Groups identifier * @param nodeIndex - index of Node which would be notes like exception */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev setNodeInGroup - adds Node to Group * function could be run only by executor * @param schainId - Groups * @param nodeIndex - index of Node which would be added to the Group */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev getSchains - gets all Schains at the system * @return array of hashes by Schain names */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev getSchainsPartOfNode - gets occupied space for given Schain * @param schainId - hash by Schain name * @return occupied space */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev getSchainListSize - gets number of created Schains at the system by owner * @param from - owner of Schain * return number of Schains */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev getSchainIdsByAddress - gets array of hashes by Schain names which owned by `from` * @param from - owner of some Schains * @return array of hashes by Schain names */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev getSchainIdsForNode - returns array of hashes by Schain names, * which given Node composed * @param nodeIndex - index of Node * @return array of hashes by Schain names */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev isSchainNameAvailable - checks is given name available * Need to delete - copy of web3.utils.soliditySha3 * @param name - possible new name of Schain * @return if available - true, else - false */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0); } /** * @dev isTimeExpired - checks is Schain lifetime expired * @param schainId - hash by Schain name * @return if expired - true, else - false */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev isOwnerAddress - checks is `from` - owner of `schainId` Schain * @param from - owner of Schain * @param schainId - hash by Schain name * @return if owner - true, else - false */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev getNumberOfNodesInGroup - shows number of Nodes in Group * @param schainId - Groups identifier * @return number of Nodes in Group */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev getNodesInGroup - shows Nodes in Group * @param schainId - Groups identifier * @return array of indexes of Nodes in Group */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev getNodeIndexInGroup - looks for Node in Group * @param schainId - Groups identifier * @param nodeId - Nodes identifier * @return index of Node in Group */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; } /** * @dev addSchainForNode - adds Schain hash to Node * function could be run only by executor * @param nodeIndex - index of Node * @param schainId - hash by Schain name */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); } else { schainsForNodes[nodeIndex][holesForNodes[nodeIndex][0]] = schainId; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForNodes[nodeIndex].length; i++) { if (min > holesForNodes[nodeIndex][i]) { min = holesForNodes[nodeIndex][i]; index = i; } } if (min == uint(-1)) { delete holesForNodes[nodeIndex]; } else { holesForNodes[nodeIndex][0] = min; holesForNodes[nodeIndex][index] = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; holesForNodes[nodeIndex].pop(); } } } /** * @dev removesSchainForNode - clean given Node of Schain * function could be run only by executor * @param nodeIndex - index of Node * @param schainIndex - index of Schain in schainsForNodes array by this Node */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev getLengthOfSchainsForNode - returns number of Schains which contain given Node * @param nodeIndex - index of Node * @return number of Schains */ function getLengthOfSchainsForNode(uint nodeIndex) public view returns (uint) { return schainsForNodes[nodeIndex].length; } /** * @dev findSchainAtSchainsForNode - finds index of Schain at schainsForNode array * @param nodeIndex - index of Node at common array of Nodes * @param schainId - hash of name of Schain * @return index of Schain at schainsForNode array */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { uint length = getLengthOfSchainsForNode(nodeIndex); for (uint i = 0; i < length; i++) { if (schainsForNodes[nodeIndex][i] == schainId) { return i; } } return length; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev _generateGroup - generates Group for Schain * @param schainId - index of Group */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev findNode - find local index of Node in Schain * @param schainId - Groups identifier * @param nodeIndex - global index of Node * @return local index of Node in Schain */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } contract SkaleDKG is Permissions, ISkaleDKG { struct Channel { bool active; uint n; uint startedBlockTimestamp; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; uint startAlrightTimestamp; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccesfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; event ChannelOpened(bytes32 groupIndex); event ChannelClosed(bytes32 groupIndex); event BroadcastAndKeyShare( bytes32 indexed groupIndex, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyStorage.KeyShare[] secretKeyContribution ); event AllDataReceived(bytes32 indexed groupIndex, uint nodeIndex); event SuccessfulDKG(bytes32 indexed groupIndex); event BadGuy(uint nodeIndex); event FailedDKG(bytes32 indexed groupIndex); event ComplaintSent(bytes32 indexed groupIndex, uint indexed fromNodeIndex, uint indexed toNodeIndex); event NewGuy(uint nodeIndex); event ComplaintError(string error); modifier correctGroup(bytes32 groupIndex) { require(channels[groupIndex].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 groupIndex) { if (!channels[groupIndex].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 groupIndex, uint nodeIndex) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); require( index < channels[groupIndex].n, "Node is not in this group"); _; } function openChannel(bytes32 groupIndex) external override allowTwo("Schains","NodeRotation") { _openChannel(groupIndex); } function deleteChannel(bytes32 groupIndex) external override allow("SchainsInternal") { require(channels[groupIndex].active, "Channel is not created"); delete channels[groupIndex]; delete dkgProcess[groupIndex]; delete complaints[groupIndex]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(groupIndex); } function broadcast( bytes32 groupIndex, uint nodeIndex, G2Operations.G2Point[] calldata verificationVector, KeyStorage.KeyShare[] calldata secretKeyContribution ) external correctGroup(groupIndex) correctNode(groupIndex, nodeIndex) { require(_isNodeByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); uint n = channels[groupIndex].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); _isBroadcast( groupIndex, nodeIndex, secretKeyContribution, verificationVector ); KeyStorage keyStorage = KeyStorage(contractManager.getContract("KeyStorage")); keyStorage.adding(groupIndex, verificationVector[0]); keyStorage.computePublicValues(groupIndex, verificationVector); emit BroadcastAndKeyShare( groupIndex, nodeIndex, verificationVector, secretKeyContribution ); } function complaint(bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex) external correctGroupWithoutRevert(groupIndex) correctNode(groupIndex, fromNodeIndex) correctNode(groupIndex, toNodeIndex) { require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); bool broadcasted = _isBroadcasted(groupIndex, toNodeIndex); if (broadcasted && complaints[groupIndex].nodeToComplaint == uint(-1)) { // incorrect data or missing alright if ( isEveryoneBroadcasted(groupIndex) && startAlrightTimestamp[groupIndex].add(COMPLAINT_TIMELIMIT) <= block.timestamp && !isAllDataReceived(groupIndex, toNodeIndex) ) { // missing alright _finalizeSlashing(groupIndex, toNodeIndex); } else { // incorrect data complaints[groupIndex].nodeToComplaint = toNodeIndex; complaints[groupIndex].fromNodeToComplaint = fromNodeIndex; complaints[groupIndex].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(groupIndex, fromNodeIndex, toNodeIndex); } } else if (broadcasted && complaints[groupIndex].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[groupIndex].startComplaintBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp) { _finalizeSlashing(groupIndex, complaints[groupIndex].nodeToComplaint); } else { emit ComplaintError("The same complaint rejected"); } } else if (!broadcasted) { // not broadcasted in 30 min if (channels[groupIndex].startedBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp) { _finalizeSlashing(groupIndex, toNodeIndex); } else { emit ComplaintError("Complaint sent too early"); } } else { emit ComplaintError("One complaint is already sent"); } } function response( bytes32 groupIndex, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point calldata multipliedShare ) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) { require(complaints[groupIndex].nodeToComplaint == fromNodeIndex, "Not this Node"); require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); bool verificationResult = KeyStorage(contractManager.getContract("KeyStorage")).verify( groupIndex, complaints[groupIndex].nodeToComplaint, complaints[groupIndex].fromNodeToComplaint, secretNumber, multipliedShare ); uint badNode = (verificationResult ? complaints[groupIndex].fromNodeToComplaint : complaints[groupIndex].nodeToComplaint); _finalizeSlashing(groupIndex, badNode); } function alright(bytes32 groupIndex, uint fromNodeIndex) external correctGroup(groupIndex) correctNode(groupIndex, fromNodeIndex) { require(_isNodeByMessageSender(fromNodeIndex, msg.sender), "Node does not exist for message sender"); uint index = _nodeIndexInSchain(groupIndex, fromNodeIndex); uint numberOfParticipant = channels[groupIndex].n; require(numberOfParticipant == dkgProcess[groupIndex].numberOfBroadcasted, "Still Broadcasting phase"); require(!dkgProcess[groupIndex].completed[index], "Node is already alright"); dkgProcess[groupIndex].completed[index] = true; dkgProcess[groupIndex].numberOfCompleted++; emit AllDataReceived(groupIndex, fromNodeIndex); if (dkgProcess[groupIndex].numberOfCompleted == numberOfParticipant) { _setSuccesfulDKG(groupIndex); } } function getChannelStartedTime(bytes32 groupIndex) external view returns (uint) { return channels[groupIndex].startedBlockTimestamp; } function getNumberOfBroadcasted(bytes32 groupIndex) external view returns (uint) { return dkgProcess[groupIndex].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 groupIndex) external view returns (uint) { return dkgProcess[groupIndex].numberOfCompleted; } function getTimeOfLastSuccesfulDKG(bytes32 groupIndex) external view returns (uint) { return lastSuccesfulDKG[groupIndex]; } function getComplaintData(bytes32 groupIndex) external view returns (uint, uint) { return (complaints[groupIndex].fromNodeToComplaint, complaints[groupIndex].nodeToComplaint); } function getComplaintStartedTime(bytes32 groupIndex) external view returns (uint) { return complaints[groupIndex].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 groupIndex) external view returns (uint) { return startAlrightTimestamp[groupIndex]; } function isChannelOpened(bytes32 groupIndex) external override view returns (bool) { return channels[groupIndex].active; } function isLastDKGSuccesful(bytes32 groupIndex) external override view returns (bool) { return channels[groupIndex].startedBlockTimestamp <= lastSuccesfulDKG[groupIndex]; } function isBroadcastPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return channels[groupIndex].active && index < channels[groupIndex].n && _isNodeByMessageSender(nodeIndex, msg.sender) && !dkgProcess[groupIndex].broadcasted[index]; } function isComplaintPossible( bytes32 groupIndex, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { uint indexFrom = _nodeIndexInSchain(groupIndex, fromNodeIndex); uint indexTo = _nodeIndexInSchain(groupIndex, toNodeIndex); bool complaintSending = ( complaints[groupIndex].nodeToComplaint == uint(-1) && dkgProcess[groupIndex].broadcasted[indexTo] ) || ( dkgProcess[groupIndex].broadcasted[indexTo] && complaints[groupIndex].startComplaintBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp && complaints[groupIndex].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[groupIndex].broadcasted[indexTo] && complaints[groupIndex].nodeToComplaint == uint(-1) && channels[groupIndex].startedBlockTimestamp.add(COMPLAINT_TIMELIMIT) <= block.timestamp ); return channels[groupIndex].active && indexFrom < channels[groupIndex].n && indexTo < channels[groupIndex].n && _isNodeByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } function isAlrightPossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return channels[groupIndex].active && index < channels[groupIndex].n && _isNodeByMessageSender(nodeIndex, msg.sender) && channels[groupIndex].n == dkgProcess[groupIndex].numberOfBroadcasted && !dkgProcess[groupIndex].completed[index]; } function isResponsePossible(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return channels[groupIndex].active && index < channels[groupIndex].n && _isNodeByMessageSender(nodeIndex, msg.sender) && complaints[groupIndex].nodeToComplaint == nodeIndex; } function isNodeBroadcasted(bytes32 groupIndex, uint nodeIndex) external view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return index < channels[groupIndex].n && dkgProcess[groupIndex].broadcasted[index]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function isEveryoneBroadcasted(bytes32 groupIndex) public view returns (bool) { return channels[groupIndex].n == dkgProcess[groupIndex].numberOfBroadcasted; } function isAllDataReceived(bytes32 groupIndex, uint nodeIndex) public view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return dkgProcess[groupIndex].completed[index]; } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } function _setSuccesfulDKG(bytes32 groupIndex) internal { lastSuccesfulDKG[groupIndex] = now; channels[groupIndex].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(groupIndex); emit SuccessfulDKG(groupIndex); } function _openChannel(bytes32 groupIndex) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(groupIndex); channels[groupIndex].active = true; channels[groupIndex].n = len; delete dkgProcess[groupIndex].completed; delete dkgProcess[groupIndex].broadcasted; dkgProcess[groupIndex].broadcasted = new bool[](len); dkgProcess[groupIndex].completed = new bool[](len); complaints[groupIndex].fromNodeToComplaint = uint(-1); complaints[groupIndex].nodeToComplaint = uint(-1); delete complaints[groupIndex].startComplaintBlockTimestamp; delete dkgProcess[groupIndex].numberOfBroadcasted; delete dkgProcess[groupIndex].numberOfCompleted; channels[groupIndex].startedBlockTimestamp = now; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(groupIndex); emit ChannelOpened(groupIndex); } function _finalizeSlashing(bytes32 groupIndex, uint badNode) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(groupIndex); if (schainsInternal.isAnyFreeNode(groupIndex)) { uint newNode = nodeRotation.rotateNode( badNode, groupIndex, false ); emit NewGuy(newNode); } else { _openChannel(groupIndex); schainsInternal.removeNodeFromSchain( badNode, groupIndex ); channels[groupIndex].active = false; } Punisher(contractManager.getContract("Punisher")).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function _isBroadcast( bytes32 groupIndex, uint nodeIndex, KeyStorage.KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) private { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); require(!dkgProcess[groupIndex].broadcasted[index], "This node is already broadcasted"); dkgProcess[groupIndex].broadcasted[index] = true; dkgProcess[groupIndex].numberOfBroadcasted++; if (dkgProcess[groupIndex].numberOfBroadcasted == channels[groupIndex].n) { startAlrightTimestamp[groupIndex] = now; } KeyStorage(contractManager.getContract("KeyStorage")).addBroadcastedData( groupIndex, index, secretKeyContribution, verificationVector ); } function _isBroadcasted(bytes32 groupIndex, uint nodeIndex) private view returns (bool) { uint index = _nodeIndexInSchain(groupIndex, nodeIndex); return dkgProcess[groupIndex].broadcasted[index]; } function _nodeIndexInSchain(bytes32 schainId, uint nodeIndex) private view returns (uint) { return SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, nodeIndex); } function _isNodeByMessageSender(uint nodeIndex, address from) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return nodes.isNodeExist(from, nodeIndex); } } contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); event BountyGot( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce}); nodes.createNode(msg.sender, params); // uint nodeIndex = nodes.createNode(msg.sender, params); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.addMonitor(nodeIndex); } function nodeExit(uint nodeIndex) external { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } bool completed; bool isSchains = false; if (schainsInternal.getActiveSchain(nodeIndex) != bytes32(0)) { completed = nodeRotation.exitFromSchain(nodeIndex); isSchains = true; } else { completed = true; } if (completed) { require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime(nodeIndex, now.add(isSchains ? constants.rotationDelay() : 0)); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.removeCheckedNodes(nodeIndex); // monitors.deleteMonitor(nodeIndex); nodes.deleteNodeForValidator(validatorId, nodeIndex); } } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } // function sendVerdict(uint fromMonitorIndex, Monitors.Verdict calldata verdict) external { // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // require(nodes.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // // additional checks for monitoring inside sendVerdict // monitors.sendVerdict(fromMonitorIndex, verdict); // } // function sendVerdicts(uint fromMonitorIndex, Monitors.Verdict[] calldata verdicts) external { // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // require(nodes.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // for (uint i = 0; i < verdicts.length; i++) { // // additional checks for monitoring inside sendVerdict // monitors.sendVerdict(fromMonitorIndex, verdicts[i]); // } // } function getBounty(uint nodeIndex) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require( nodes.isNodeActive(nodeIndex) || nodes.isNodeLeaving(nodeIndex), "Node is not Active and is not Leaving" ); Bounty bountyContract = Bounty(contractManager.getContract("Bounty")); uint averageDowntime; uint averageLatency; Monitors monitors = Monitors(contractManager.getContract("Monitors")); (averageDowntime, averageLatency) = monitors.calculateMetrics(nodeIndex); uint bounty = bountyContract.getBounty( nodeIndex, averageDowntime, averageLatency); nodes.changeNodeLastRewardDate(nodeIndex); // monitors.deleteMonitor(nodeIndex); // monitors.addMonitor(nodeIndex); if (bounty > 0) { _payBounty(bounty, nodes.getValidatorId(nodeIndex)); } _emitBountyEvent(nodeIndex, msg.sender, averageDowntime, averageLatency, bounty); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); // solhint-disable-next-line check-send-result skaleToken.send(address(distributor), bounty, abi.encode(validatorId)); } function _emitBountyEvent( uint nodeIndex, address from, uint averageDowntime, uint averageLatency, uint bounty ) private { Monitors monitors = Monitors(contractManager.getContract("Monitors")); uint previousBlockEvent = monitors.getLastBountyBlock(nodeIndex); monitors.setLastBountyBlock(nodeIndex); emit BountyGot( nodeIndex, from, averageDowntime, averageLatency, bounty, previousBlockEvent, block.timestamp, gasleft()); } } contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB; if (!(signature.a == 0 && signature.b == 0)) { newSignB = Fp2Operations.P.sub((signature.b % Fp2Operations.P)); } else { newSignB = signature.b; } require(G2Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G2Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; /** * @dev Sets a penalty for a given offense * Only the owner can set penalties. * * @param offense string * @param penalty uint amount of slashing for the specified penalty */ function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty for a given offense * * @param offense string * @return uint amount of slashing for the specified penalty */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUserCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Can't add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUserCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } function _totalDelegatedSatisfiesProofOfUserCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } contract TokenState is Permissions, ILocker { /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); string[] private _lockers; /** * @dev Return and update the total locked amount of a given `holder`. * * @param holder address of the token holder * @return total locked amount */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint locked = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } /** * @dev Return and update the total locked and un-delegatable amount of a given `holder`. * * @param holder address of the token holder * @return amount total slashed amount (non-transferable and non-delegatable) */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a LockerWasRemoved event. * * @param locker string name of contract to remove from locker */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a LockerWasAdded event. * * @param locker string name of contract to add to locker */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); event ValidatorWasEnabled( uint validatorId ); event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator Id. * * Requirements: * * - sender must not already have registered a validator Id. * - fee rate must be between 0 - 1000‰. Note: per mille! * * Emits ValidatorRegistered event. * * @param name string * @param description string * @param feeRate uint Fee charged on delegations by the validator per mille * @param minimumDelegationAmount uint Minimum delegation amount accepted by the validator */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate < 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the validator whitelist. Once turned off the * whitelist cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows a validator to request a new address. * * Requirements: * * - new address must not be null * - new address must not be already registered as a validator * * @param newValidatorAddress address */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a given node address. * * Requirements: * * - the given signature must be valid. * - the address must not be assigned to a validator. * * Emits NodeAddressWasAdded event. * * @param nodeAddress address * @param sig bytes signature of validator Id by node operator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a given node address from a validator. * * Emits NodeAddressWasRemoved event. * * @param nodeAddress address */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); _removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. * * @param newName string */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. * * @param newDescription string */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - validator must not have already enabled accepting new requests */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - validator must not have already stopped accepting new requests */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } /** * @dev Returns the amount of validator bond. * * @param validatorId uint ID of validator to return the amount of locked funds * @return bondAmount uint the amount of self-delegated funds by the validator */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns a list of trusted validators. * * @return uint[] trusted validators */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } function checkMinimumDelegation(uint validatorId, uint amount) external view checkValidatorExists(validatorId) allow("DelegationController") returns (bool) { return validators[validatorId].minimumDelegationAmount <= amount ? true : false; } function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function isAuthorizedValidator(uint validatorId) external view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator with given address does not exist"); } function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } // private function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _removeNodeAddress(uint validatorId, address nodeAddress) private { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } contract Bounty is Permissions { uint public constant STAGE_LENGTH = 31558150; // 1 year uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant BOUNTY = 96250000 * 1e18; uint private _nextStage; uint private _stagePool; bool public bountyReduction; uint private _nodesPerRewardPeriod; uint private _nodesRemainingPerRewardPeriod; uint private _rewardPeriodFinished; function getBounty( uint nodeIndex, uint downtime, uint latency ) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); _refillStagePool(constantsHolder); if (_rewardPeriodFinished <= now) { _updateNodesPerRewardPeriod(constantsHolder, nodes); } uint bounty = _calculateMaximumBountyAmount(_stagePool, _nextStage, nodeIndex, constantsHolder, nodes); bounty = _reduceBounty( bounty, nodeIndex, downtime, latency, nodes, constantsHolder ); _stagePool = _stagePool.sub(bounty); _nodesRemainingPerRewardPeriod = _nodesRemainingPerRewardPeriod.sub(1); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function calculateNormalBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint stagePoolSize; uint nextStage; (stagePoolSize, nextStage) = _getStagePoolSize(constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, nextStage, nodeIndex, constantsHolder, nodes ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextStage = 0; _stagePool = 0; _rewardPeriodFinished = 0; bountyReduction = false; } // private function _calculateMaximumBountyAmount( uint stagePoolSize, uint nextStage, uint nodeIndex, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } uint numberOfRewards = _getStageBeginningTimestamp(nextStage, constantsHolder) .sub(now) .div(constantsHolder.rewardPeriod()); uint numberOfRewardsPerAllNodes = numberOfRewards.mul(_nodesPerRewardPeriod); return stagePoolSize.div( numberOfRewardsPerAllNodes.add(_nodesRemainingPerRewardPeriod) ); } function _getStageBeginningTimestamp(uint stage, ConstantsHolder constantsHolder) private view returns (uint) { return constantsHolder.launchTimestamp().add(stage.mul(STAGE_LENGTH)); } function _getStagePoolSize(ConstantsHolder constantsHolder) private view returns (uint stagePool, uint nextStage) { stagePool = _stagePool; for (nextStage = _nextStage; now >= _getStageBeginningTimestamp(nextStage, constantsHolder); ++nextStage) { stagePool += _getStageReward(_nextStage); } } function _refillStagePool(ConstantsHolder constantsHolder) private { (_stagePool, _nextStage) = _getStagePoolSize(constantsHolder); } function _updateNodesPerRewardPeriod(ConstantsHolder constantsHolder, Nodes nodes) private { _nodesPerRewardPeriod = nodes.getNumberOnlineNodes(); _nodesRemainingPerRewardPeriod = _nodesPerRewardPeriod; _rewardPeriodFinished = now.add(uint(constantsHolder.rewardPeriod())); } function _getStageReward(uint stage) private pure returns (uint) { if (stage >= 6) { return BOUNTY.div(2 ** stage.sub(6).div(3)); } else { if (stage == 0) { return YEAR1_BOUNTY; } else if (stage == 1) { return YEAR2_BOUNTY; } else if (stage == 2) { return YEAR3_BOUNTY; } else if (stage == 3) { return YEAR4_BOUNTY; } else if (stage == 4) { return YEAR5_BOUNTY; } else { return YEAR6_BOUNTY; } } } function _reduceBounty( uint bounty, uint nodeIndex, uint downtime, uint latency, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = _reduceBountyByDowntime(bounty, nodeIndex, downtime, nodes, constants); if (latency > constants.allowableLatency()) { // reduce bounty because latency is too big reducedBounty = reducedBounty.mul(constants.allowableLatency()).div(latency); } if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _reduceBountyByDowntime( uint bounty, uint nodeIndex, uint downtime, Nodes nodes, ConstantsHolder constants ) private view returns (uint reducedBounty) { reducedBounty = bounty; uint getBountyDeadline = uint(nodes.getNodeLastRewardDate(nodeIndex)) .add(constants.rewardPeriod()) .add(constants.deltaPeriod()); uint numberOfExpiredIntervals; if (now > getBountyDeadline) { numberOfExpiredIntervals = now.sub(getBountyDeadline).div(constants.checkTime()); } else { numberOfExpiredIntervals = 0; } uint normalDowntime = uint(constants.rewardPeriod()) .sub(constants.deltaPeriod()) .div(constants.checkTime()) .div(constants.DOWNTIME_THRESHOLD_PART()); uint totalDowntime = downtime.add(numberOfExpiredIntervals); if (totalDowntime > normalDowntime) { // reduce bounty because downtime is too big uint penalty = bounty .mul(totalDowntime) .div( uint(constants.rewardPeriod()).sub(constants.deltaPeriod()) .div(constants.checkTime()) ); if (bounty > penalty) { reducedBounty = bounty.sub(penalty); } else { reducedBounty = 0; } } } } contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/8 of Node) uint8 public constant MEDIUM_DIVISOR = 8; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 3; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint public firstDelegationsMonth; /** * Set reward and delta periods to new one, run only by owner. This function * only for tests. * @param newRewardPeriod - new Reward period * @param newDeltaPeriod - new Delta period */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * Set new check time. This function only for tests. * @param newCheckTime - new check time */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * Set latency new one in ms, run only by owner. This function * only for tests. * @param newAllowableLatency - new Allowable Latency */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Can't set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setFirstDelegationsMonth(uint month) external onlyOwner { firstDelegationsMonth = month; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 8; } } contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * @param validatorId uint ID of validator to receive delegation proposal * @param amount uint amount of proposed delegation * @param delegationPeriod uint period of proposed delegation * @param info string extra information provided by the token holder (if any) */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); TokenState tokenState = TokenState(contractManager.getContract("TokenState")); require( validatorService.checkMinimumDelegation(validatorId, amount), "Amount does not meet the validator's minimum delegation amount"); require( validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require( delegationPeriodManager.isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); require( validatorService.isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = skaleToken.balanceOf(msg.sender); uint forbiddenForDelegation = tokenState.getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See ILocker. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows a token holder to cancel a delegation proposal. * * Requirements: * * - the sender must be the token holder of the delegation proposal. * - the delegation must still be in a PROPOSED state. * * Emits a DelegationRequestCanceledByUser event. * * @param delegationId uint ID of delegation proposal */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a DelegationAccepted event. * * @param delegationId uint ID of delegation proposal */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( validatorService.checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); tokenLaunchLocker.handleDelegationAdd( delegations[delegationId].holder, delegationId, delegations[delegationId].amount, delegations[delegationId].started); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } /** * @dev Allows a delegator to undelegate a specific delegation. * * Requirements: * * - the sender must be the delegator. * - the delegation must be in DELEGATED state. * * Emits an UndelegationRequested event. * * @param delegationId uint ID of delegation to undelegate */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); tokenLaunchLocker.handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); emit UndelegationRequested(delegationId); } /** * @dev Allows the Punisher to confiscate an `amount` of stake from * `validatorId` by slashing. This slashes all delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manger to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * See Punisher. * * Emits a SlashingEvent. * * @param validatorId uint validator to slash * @param amount uint amount to slash * */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); } function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allow("Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function getAndUpdateDelegatedToValidator(uint validatorId, uint month) public allow("Nodes") returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. * * @param delegationId uint ID of the delegation */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); if (_getCurrentMonth() == timeHelpers.timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); require( _lockedInPendingDelegations[holder].month == currentMonth, "There are no delegation requests this month"); require(_lockedInPendingDelegations[holder].amount >= amount, "Unlocking amount is too big"); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); return timeHelpers.getCurrentMonth(); } function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getContract("Punisher")); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < constantsHolder.limitValidatorsPerDelegator() ), "Limit of validators is reached" ); require( _getCurrentMonth() >= constantsHolder.firstDelegationsMonth(), "Delegations are not allowed" ); } } contract DelegationPeriodManager is Permissions { /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); mapping (uint => uint) public stakeMultipliers; /** * @dev Creates a new available delegation period and return in the network. * Only the owner may set new delegation period and returns in the network. * * Emits a DelegationPeriodWasSet event. * * @param monthsCount uint delegation duration in months * @param stakeMultiplier uint return for delegation */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. * * @param monthsCount uint delegation duration in months * @return bool True if delegation period is allowed */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0 ? true : false; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[3] = 100; // 3 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when a bounty is withdrawn by the token holder. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn by the validator. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when a bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function addBroadcastedData( bytes32 groupIndex, uint indexInSchain, KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) external allow("SkaleDKG") { for (uint i = 0; i < secretKeyContribution.length; ++i) { if (i < _data[groupIndex][indexInSchain].secretKeyContribution.length) { _data[groupIndex][indexInSchain].secretKeyContribution[i] = secretKeyContribution[i]; } else { _data[groupIndex][indexInSchain].secretKeyContribution.push(secretKeyContribution[i]); } } while (_data[groupIndex][indexInSchain].secretKeyContribution.length > secretKeyContribution.length) { _data[groupIndex][indexInSchain].secretKeyContribution.pop(); } for (uint i = 0; i < verificationVector.length; ++i) { if (i < _data[groupIndex][indexInSchain].verificationVector.length) { _data[groupIndex][indexInSchain].verificationVector[i] = verificationVector[i]; } else { _data[groupIndex][indexInSchain].verificationVector.push(verificationVector[i]); } } while (_data[groupIndex][indexInSchain].verificationVector.length > verificationVector.length) { _data[groupIndex][indexInSchain].verificationVector.pop(); } } function deleteKey(bytes32 groupIndex) external allow("SkaleDKG") { _previousSchainsPublicKeys[groupIndex].push(_schainsPublicKeys[groupIndex]); delete _schainsPublicKeys[groupIndex]; } function initPublicKeyInProgress(bytes32 groupIndex) external allow("SkaleDKG") { _publicKeysInProgress[groupIndex] = G2Operations.getG2Zero(); delete _schainsNodesPublicKeys[groupIndex]; } function adding(bytes32 groupIndex, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[groupIndex] = value.addG2(_publicKeysInProgress[groupIndex]); } function finalizePublicKey(bytes32 groupIndex) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(groupIndex)) { _previousSchainsPublicKeys[groupIndex].push(_schainsPublicKeys[groupIndex]); } _schainsPublicKeys[groupIndex] = _publicKeysInProgress[groupIndex]; delete _publicKeysInProgress[groupIndex]; } function computePublicValues(bytes32 groupIndex, G2Operations.G2Point[] calldata verificationVector) external allow("SkaleDKG") { if (_schainsNodesPublicKeys[groupIndex].length == 0) { for (uint i = 0; i < verificationVector.length; ++i) { require(verificationVector[i].isG2(), "Incorrect g2 point verVec 1"); G2Operations.G2Point memory tmp = verificationVector[i]; _schainsNodesPublicKeys[groupIndex].push(tmp); require(_schainsNodesPublicKeys[groupIndex][i].isG2(), "Incorrect g2 point schainNodesPubKey 1"); } while (_schainsNodesPublicKeys[groupIndex].length > verificationVector.length) { _schainsNodesPublicKeys[groupIndex].pop(); } } else { require(_schainsNodesPublicKeys[groupIndex].length == verificationVector.length, "Incorrect length"); for (uint i = 0; i < _schainsNodesPublicKeys[groupIndex].length; ++i) { require(verificationVector[i].isG2(), "Incorrect g2 point verVec 2"); require(_schainsNodesPublicKeys[groupIndex][i].isG2(), "Incorrect g2 point schainNodesPubKey 2"); _schainsNodesPublicKeys[groupIndex][i] = verificationVector[i].addG2( _schainsNodesPublicKeys[groupIndex][i] ); require(_schainsNodesPublicKeys[groupIndex][i].isG2(), "Incorrect g2 point addition"); } } } function verify( bytes32 groupIndex, uint nodeToComplaint, uint fromNodeToComplaint, uint secretNumber, G2Operations.G2Point memory multipliedShare ) external view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint index = schainsInternal.getNodeIndexInGroup(groupIndex, nodeToComplaint); uint secret = _decryptMessage(groupIndex, secretNumber, nodeToComplaint, fromNodeToComplaint); G2Operations.G2Point[] memory verificationVector = _data[groupIndex][index].verificationVector; G2Operations.G2Point memory value = G2Operations.getG2Zero(); G2Operations.G2Point memory tmp = G2Operations.getG2Zero(); if (multipliedShare.isG2()) { for (uint i = 0; i < verificationVector.length; i++) { tmp = verificationVector[i].mulG2(index.add(1) ** i); value = tmp.addG2(value); } return value.isEqual(multipliedShare) && _checkCorrectMultipliedShare(multipliedShare, secret); } return false; } function getBroadcastedData(bytes32 groupIndex, uint nodeIndex) external view returns (KeyShare[] memory, G2Operations.G2Point[] memory) { uint indexInSchain = SchainsInternal(contractManager.getContract("SchainsInternal")).getNodeIndexInGroup( groupIndex, nodeIndex ); if ( _data[groupIndex][indexInSchain].secretKeyContribution.length == 0 && _data[groupIndex][indexInSchain].verificationVector.length == 0 ) { KeyShare[] memory keyShare = new KeyShare[](0); G2Operations.G2Point[] memory g2Point = new G2Operations.G2Point[](0); return (keyShare, g2Point); } return ( _data[groupIndex][indexInSchain].secretKeyContribution, _data[groupIndex][indexInSchain].verificationVector ); } function getSecretKeyShare(bytes32 groupIndex, uint nodeIndex, uint index) external view returns (bytes32) { uint indexInSchain = SchainsInternal(contractManager.getContract("SchainsInternal")).getNodeIndexInGroup( groupIndex, nodeIndex ); return (_data[groupIndex][indexInSchain].secretKeyContribution[index].share); } function getVerificationVector(bytes32 groupIndex, uint nodeIndex) external view returns (G2Operations.G2Point[] memory) { uint indexInSchain = SchainsInternal(contractManager.getContract("SchainsInternal")).getNodeIndexInGroup( groupIndex, nodeIndex ); return (_data[groupIndex][indexInSchain].verificationVector); } function getCommonPublicKey(bytes32 groupIndex) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[groupIndex]; } function getPreviousPublicKey(bytes32 groupIndex) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[groupIndex].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[groupIndex][length - 1]; } function getAllPreviousPublicKeys(bytes32 groupIndex) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[groupIndex]; } function getBLSPublicKey(bytes32 groupIndex, uint nodeIndex) external view returns (G2Operations.G2Point memory) { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")).getNodeIndexInGroup( groupIndex, nodeIndex ); return _calculateBlsPublicKey(groupIndex, index); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _calculateBlsPublicKey(bytes32 groupIndex, uint index) private view returns (G2Operations.G2Point memory) { G2Operations.G2Point memory publicKey = G2Operations.getG2Zero(); G2Operations.G2Point memory tmp = G2Operations.getG2Zero(); G2Operations.G2Point[] memory publicValues = _schainsNodesPublicKeys[groupIndex]; for (uint i = 0; i < publicValues.length; ++i) { require(publicValues[i].isG2(), "Incorrect g2 point publicValuesComponent"); tmp = publicValues[i].mulG2(Precompiled.bigModExp(index.add(1), i, Fp2Operations.P)); require(tmp.isG2(), "Incorrect g2 point tmp"); publicKey = tmp.addG2(publicKey); require(publicKey.isG2(), "Incorrect g2 point publicKey"); } return publicKey; } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getCommonPublicKey( uint256 secretNumber, uint fromNodeToComplaint ) private view returns (bytes32) { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey(fromNodeToComplaint); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); return bytes32(pkX); } function _decryptMessage( bytes32 groupIndex, uint secretNumber, uint nodeToComplaint, uint fromNodeToComplaint ) private view returns (uint) { bytes32 key = _getCommonPublicKey(secretNumber, fromNodeToComplaint); // Decrypt secret key contribution SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint index = schainsInternal.getNodeIndexInGroup(groupIndex, fromNodeToComplaint); uint indexOfNode = schainsInternal.getNodeIndexInGroup(groupIndex, nodeToComplaint); uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( _data[groupIndex][indexOfNode].secretKeyContribution[index].share, key ); return secret; } function _checkCorrectMultipliedShare(G2Operations.G2Point memory multipliedShare, uint secret) private view returns (bool) { G2Operations.G2Point memory tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G2Operations.getG1(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); if (!(share.a == 0 && share.b == 0)) { share.b = Fp2Operations.P.sub((share.b % Fp2Operations.P)); } require(G2Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2(); require(G2Operations.isG2(tmp), "tmp not in g2"); return Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } } contract Monitors is Permissions { using StringUtils for string; using SafeCast for uint; struct Verdict { uint toNodeIndex; uint32 downtime; uint32 latency; } struct CheckedNode { uint nodeIndex; uint time; } struct CheckedNodeWithIp { uint nodeIndex; uint time; bytes4 ip; } mapping (bytes32 => CheckedNode[]) public checkedNodes; mapping (bytes32 => uint[][]) public verdicts; mapping (bytes32 => uint[]) public groupsForMonitors; mapping (bytes32 => uint) public lastVerdictBlocks; mapping (bytes32 => uint) public lastBountyBlocks; event MonitorCreated( uint nodeIndex, bytes32 monitorIndex, uint numberOfMonitors, uint[] nodesInGroup, uint time, uint gasSpend ); event VerdictWasSent( uint indexed fromMonitorIndex, uint indexed toNodeIndex, uint32 downtime, uint32 latency, bool status, uint previousBlockEvent, uint time, uint gasSpend ); event MetricsWereCalculated( uint forNodeIndex, uint32 averageDowntime, uint32 averageLatency, uint time, uint gasSpend ); event PeriodsWereSet( uint rewardPeriod, uint deltaPeriod, uint time, uint gasSpend ); event MonitorRotated( bytes32 monitorIndex, uint newNode ); /** * addMonitor - setup monitors of node */ function addMonitor(uint nodeIndex) external allow("SkaleManager") { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); _generateGroup(monitorIndex, nodeIndex, constantsHolder.NUMBER_OF_MONITORS()); CheckedNode memory checkedNode = _getCheckedNodeData(nodeIndex); for (uint i = 0; i < groupsForMonitors[monitorIndex].length; i++) { bytes32 index = keccak256(abi.encodePacked(groupsForMonitors[monitorIndex][i])); addCheckedNode(index, checkedNode); } emit MonitorCreated( nodeIndex, monitorIndex, groupsForMonitors[monitorIndex].length, groupsForMonitors[monitorIndex], block.timestamp, gasleft() ); } function deleteMonitor(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); while (verdicts[keccak256(abi.encodePacked(nodeIndex))].length > 0) { verdicts[keccak256(abi.encodePacked(nodeIndex))].pop(); } uint[] memory nodesInGroup = groupsForMonitors[monitorIndex]; uint index; bytes32 monitoringIndex; for (uint i = 0; i < nodesInGroup.length; i++) { monitoringIndex = keccak256(abi.encodePacked(nodesInGroup[i])); (index, ) = _find(monitoringIndex, nodeIndex); if (index < checkedNodes[monitoringIndex].length) { if (index != checkedNodes[monitoringIndex].length.sub(1)) { checkedNodes[monitoringIndex][index] = checkedNodes[monitoringIndex][checkedNodes[monitoringIndex].length.sub(1)]; } checkedNodes[monitoringIndex].pop(); } } delete groupsForMonitors[monitorIndex]; } function removeCheckedNodes(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); delete checkedNodes[monitorIndex]; } function sendVerdict(uint fromMonitorIndex, Verdict calldata verdict) external allow("SkaleManager") { uint index; uint time; bytes32 monitorIndex = keccak256(abi.encodePacked(fromMonitorIndex)); (index, time) = _find(monitorIndex, verdict.toNodeIndex); require(time > 0, "Checked Node does not exist in MonitorsArray"); if (time <= block.timestamp) { if (index != checkedNodes[monitorIndex].length.sub(1)) { checkedNodes[monitorIndex][index] = checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; } delete checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; checkedNodes[monitorIndex].pop(); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bool receiveVerdict = time.add(constantsHolder.deltaPeriod()) > block.timestamp; if (receiveVerdict) { verdicts[keccak256(abi.encodePacked(verdict.toNodeIndex))].push( [uint(verdict.downtime), uint(verdict.latency)] ); } _emitVerdictsEvent(fromMonitorIndex, verdict, receiveVerdict); } } function calculateMetrics(uint nodeIndex) external allow("SkaleManager") returns (uint averageDowntime, uint averageLatency) { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); uint lengthOfArray = getLengthOfMetrics(monitorIndex); uint[] memory downtimeArray = new uint[](lengthOfArray); uint[] memory latencyArray = new uint[](lengthOfArray); for (uint i = 0; i < lengthOfArray; i++) { downtimeArray[i] = verdicts[monitorIndex][i][0]; latencyArray[i] = verdicts[monitorIndex][i][1]; } if (lengthOfArray > 0) { averageDowntime = _median(downtimeArray); averageLatency = _median(latencyArray); } delete verdicts[monitorIndex]; } function setLastBountyBlock(uint nodeIndex) external allow("SkaleManager") { lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))] = block.number; } function getCheckedArray(bytes32 monitorIndex) external view returns (CheckedNodeWithIp[] memory checkedNodesWithIp) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNodesWithIp = new CheckedNodeWithIp[](checkedNodes[monitorIndex].length); for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { checkedNodesWithIp[i].nodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodesWithIp[i].time = checkedNodes[monitorIndex][i].time; checkedNodesWithIp[i].ip = nodes.getNodeIP(checkedNodes[monitorIndex][i].nodeIndex); } } function getLastBountyBlock(uint nodeIndex) external view returns (uint) { return lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))]; } function getNodesInGroup(bytes32 monitorIndex) external view returns (uint[] memory) { return groupsForMonitors[monitorIndex]; } function getNumberOfNodesInGroup(bytes32 monitorIndex) external view returns (uint) { return groupsForMonitors[monitorIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * Add checked node or update existing one if it is already exits */ function addCheckedNode(bytes32 monitorIndex, CheckedNode memory checkedNode) public allow("SkaleManager") { for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { if (checkedNodes[monitorIndex][i].nodeIndex == checkedNode.nodeIndex) { checkedNodes[monitorIndex][i] = checkedNode; return; } } checkedNodes[monitorIndex].push(checkedNode); } function getLastReceivedVerdictBlock(uint nodeIndex) public view returns (uint) { return lastVerdictBlocks[keccak256(abi.encodePacked(nodeIndex))]; } function getLengthOfMetrics(bytes32 monitorIndex) public view returns (uint) { return verdicts[monitorIndex].length; } function _generateGroup(bytes32 monitorIndex, uint nodeIndex, uint numberOfNodes) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint[] memory activeNodes = nodes.getActiveNodeIds(); uint numberOfNodesInGroup; uint availableAmount = activeNodes.length.sub((nodes.isNodeActive(nodeIndex)) ? 1 : 0); if (numberOfNodes > availableAmount) { numberOfNodesInGroup = availableAmount; } else { numberOfNodesInGroup = numberOfNodes; } uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), monitorIndex))); for (uint i = 0; i < numberOfNodesInGroup; ++i) { uint index = random % (activeNodes.length.sub(ignoringTail)); if (activeNodes[index] == nodeIndex) { _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; index = random % (activeNodes.length.sub(ignoringTail)); } groupsForMonitors[monitorIndex].push(activeNodes[index]); _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; } } function _median(uint[] memory values) private pure returns (uint) { if (values.length < 1) { revert("Can't calculate _median of empty array"); } _quickSort(values, 0, values.length.sub(1)); return values[values.length.div(2)]; } function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } function _find(bytes32 monitorIndex, uint nodeIndex) private view returns (uint index, uint time) { index = checkedNodes[monitorIndex].length; time = 0; for (uint i = 0; i < checkedNodes[monitorIndex].length; i++) { uint checkedNodeNodeIndex; uint checkedNodeTime; checkedNodeNodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodeTime = checkedNodes[monitorIndex][i].time; if (checkedNodeNodeIndex == nodeIndex && (time == 0 || checkedNodeTime < time)) { index = i; time = checkedNodeTime; } } } function _quickSort(uint[] memory array, uint left, uint right) private pure { uint leftIndex = left; uint rightIndex = right; uint middle = array[right.add(left).div(2)]; while (leftIndex <= rightIndex) { while (array[leftIndex] < middle) { leftIndex++; } while (middle < array[rightIndex]) { rightIndex--; } if (leftIndex <= rightIndex) { (array[leftIndex], array[rightIndex]) = (array[rightIndex], array[leftIndex]); leftIndex++; rightIndex = (rightIndex > 0 ? rightIndex.sub(1) : 0); } } if (left < rightIndex) _quickSort(array, left, rightIndex); if (leftIndex < right) _quickSort(array, leftIndex, right); } function _getCheckedNodeData(uint nodeIndex) private view returns (CheckedNode memory checkedNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNode.nodeIndex = nodeIndex; checkedNode.time = nodes.getNodeNextRewardDate(nodeIndex).sub(constantsHolder.deltaPeriod()); } function _emitVerdictsEvent( uint fromMonitorIndex, Verdict memory verdict, bool receiveVerdict ) private { uint previousBlockEvent = getLastReceivedVerdictBlock(verdict.toNodeIndex); lastVerdictBlocks[keccak256(abi.encodePacked(verdict.toNodeIndex))] = block.number; emit VerdictWasSent( fromMonitorIndex, verdict.toNodeIndex, verdict.downtime, verdict.latency, receiveVerdict, previousBlockEvent, block.timestamp, gasleft() ); } } contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; /** * nodeIndex - index of Node which is in process of rotation(left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No any free Nodes for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str()); string memory dkgRevert = "DKG proccess did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccesful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { if (rotations[schainIndex].nodeIndex != rotations[schainIndex].newNodeIndex) { return rotations[schainIndex]; } return Rotation(0, 0, 0, 0); } function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev selectNodeToGroup - pseudo-randomly select new Node for Schain * @param schainId - hash of name of Schain * @return nodeIndex - global index of Node */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No any free Nodes for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); } function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; // informs that Node is created event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint time, uint gasSpend ); // informs that node is fully finished quitting from the system event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); // informs that owner starts the procedure of quitting the Node from the system event ExitInited( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } /** * @dev removeSpaceFromFractionalNode - occupies space from Fractional Node * function could be run only by Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be occupied */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev adSpaceToFractionalNode - returns space to Fractional Node * function could be run only be Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be returned */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev changeNodeLastRewardDate - changes Node's last reward date * function could be run only by SkaleManager * @param nodeIndex - index of Node */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev createNode - creates new Node and add it to the Nodes contract * function could be only run by SkaleManager * @param from - owner of Node */ // * @return nodeIndex - index of Node function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name has already registered"); require(params.port > 0, "Port is zero"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, block.timestamp, gasleft()); } /** * @dev initExit - initiate a procedure of quitting the system * function could be only run by SkaleManager * @param nodeIndex - index of Node * @return true - if everything OK */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { _setNodeLeaving(nodeIndex); emit ExitInited( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev completeExit - finish a procedure of quitting the system * function could be run only by SkaleManager * @param nodeIndex - index of Node * @return amount of SKL which be returned */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); } function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function setNodeInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.In_Maintenance; } function removeNodeFromInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintence"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.Active; } function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev isTimeForReward - checks if time for reward has come * @param nodeIndex - index of Node * @return if time for reward has come - true, else - false */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return uint(nodes[nodeIndex].lastRewardDate).add(constantsHolder.rewardPeriod()) <= block.timestamp; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev getNodePort - get Node's port * @param nodeIndex - index of Node * @return port */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev isNodeLeft - checks if Node status Left * @param nodeIndex - index of Node * @return if Node status Left - true, else - false */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev getNodeNextRewardDate - get Node next reward date * @param nodeIndex - index of Node * @return Node next reward date */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes[nodeIndex].lastRewardDate.add(constantsHolder.rewardPeriod()); } /** * @dev getNumberOfNodes - get number of Nodes * @return number of Nodes */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev getNumberOfFullNodes - get number Online Nodes * @return number of active nodes plus number of leaving nodes */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev getActiveNodeIPs - get array of ips of Active Nodes * @return activeNodeIPs - array of ips of Active Nodes */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev getActiveNodesByAddress - get array of indexes of Active Nodes, which were * created by msg.sender * @return activeNodesByAddress Array of indexes of Active Nodes, which were created by msg.sender */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev getActiveNodeIds - get array of indexes of Active Nodes * @return activeNodeIds - array of indexes of Active Nodes */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev isNodeExist - checks existence of Node at this address * @param from - account address * @param nodeIndex - index of Node * @return if exist - true, else - false */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev isNodeActive - checks if Node status Active * @param nodeIndex - index of Node * @return if Node status Active - true, else - false */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev isNodeLeaving - checks if Node status Leaving * @param nodeIndex - index of Node * @return if Node status Leaving - true, else - false */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev _setNodeLeft - set Node Left * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev _setNodeLeaving - set Node Leaving * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev _addNode - adds Node to array * function could be run only by executor * @param from - owner of Node * @param name - Node name * @param ip - Node ip * @param publicIP - Node public ip * @param port - Node public port * @param publicKey - Ethereum public key * @return nodeIndex Index of Node */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } }
0x608060405234801561001057600080fd5b50600436106100b45760003560e01c8063a217fddf11610071578063a217fddf14610231578063b39e12cf14610239578063c4d66de814610241578063ca15c87314610267578063d547741f14610284578063fba45d35146102b0576100b4565b8063248a9ca3146100b95780632e91240d146100e85780632f2ff15d1461015a57806336568abe146101865780639010d07c146101b257806391d14854146101f1575b600080fd5b6100d6600480360360208110156100cf57600080fd5b5035610320565b60408051918252519081900360200190f35b610158600480360360408110156100fe57600080fd5b81019060208101813564010000000081111561011957600080fd5b82018360208201111561012b57600080fd5b8035906020019184600183028401116401000000008311171561014d57600080fd5b919350915035610335565b005b6101586004803603604081101561017057600080fd5b50803590602001356001600160a01b03166103dd565b6101586004803603604081101561019c57600080fd5b50803590602001356001600160a01b0316610449565b6101d5600480360360408110156101c857600080fd5b50803590602001356104aa565b604080516001600160a01b039092168252519081900360200190f35b61021d6004803603604081101561020757600080fd5b50803590602001356001600160a01b03166104d1565b604080519115158252519081900360200190f35b6100d66104ef565b6101d56104f4565b6101586004803603602081101561025757600080fd5b50356001600160a01b0316610503565b6100d66004803603602081101561027d57600080fd5b50356105ae565b6101586004803603604081101561029a57600080fd5b50803590602001356001600160a01b03166105c5565b6100d6600480360360208110156102c657600080fd5b8101906020810181356401000000008111156102e157600080fd5b8201836020820111156102f357600080fd5b8035906020019184600183028401116401000000008311171561031557600080fd5b50909250905061061e565b60009081526065602052604090206002015490565b61033d61066b565b61038e576040805162461bcd60e51b815260206004820152601760248201527f43616c6c6572206973206e6f7420746865206f776e6572000000000000000000604482015290519081900360640190fd5b806098600085856040516020018083838082843780830192505050925050506040516020818303038152906040528051906020012060001c815260200190815260200160002081905550505050565b600082815260656020526040902060020154610400906103fb61067c565b6104d1565b61043b5760405162461bcd60e51b815260040180806020018281038252602f815260200180610c6e602f913960400191505060405180910390fd5b6104458282610680565b5050565b61045161067c565b6001600160a01b0316816001600160a01b0316146104a05760405162461bcd60e51b815260040180806020018281038252602f815260200180610d1d602f913960400191505060405180910390fd5b61044582826106ef565b60008281526065602052604081206104c8908363ffffffff61075e16565b90505b92915050565b60008281526065602052604081206104c8908363ffffffff61076a16565b600081565b6097546001600160a01b031681565b600054610100900460ff168061051c575061051c61077f565b8061052a575060005460ff16155b6105655760405162461bcd60e51b815260040180806020018281038252602e815260200180610ccd602e913960400191505060405180910390fd5b600054610100900460ff16158015610590576000805460ff1961ff0019909116610100171660011790555b61059982610785565b8015610445576000805461ff00191690555050565b60008181526065602052604081206104cb9061082e565b6000828152606560205260409020600201546105e3906103fb61067c565b6104a05760405162461bcd60e51b8152600401808060200182810382526030815260200180610c9d6030913960400191505060405180910390fd5b600080609860008585604051602001808383808284376040805191909301818103601f19018252835280516020918201208752860196909652939093016000205498975050505050505050565b600061067781336104d1565b905090565b3390565b600082815260656020526040902061069e908263ffffffff61083916565b15610445576106ab61067c565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600082815260656020526040902061070d908263ffffffff61084e16565b156104455761071a61067c565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60006104c88383610863565b60006104c8836001600160a01b0384166108c7565b303b1590565b600054610100900460ff168061079e575061079e61077f565b806107ac575060005460ff16155b6107e75760405162461bcd60e51b815260040180806020018281038252602e815260200180610ccd602e913960400191505060405180910390fd5b600054610100900460ff16158015610812576000805460ff1961ff0019909116610100171660011790555b61081a6108df565b61082560003361043b565b61059982610991565b60006104cb82610a5b565b60006104c8836001600160a01b038416610a5f565b60006104c8836001600160a01b038416610aa9565b815460009082106108a55760405162461bcd60e51b8152600401808060200182810382526022815260200180610c4c6022913960400191505060405180910390fd5b8260000182815481106108b457fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600054610100900460ff16806108f857506108f861077f565b80610906575060005460ff16155b6109415760405162461bcd60e51b815260040180806020018281038252602e815260200180610ccd602e913960400191505060405180910390fd5b600054610100900460ff1615801561096c576000805460ff1961ff0019909116610100171660011790555b610974610b6f565b61097c610b6f565b801561098e576000805461ff00191690555b50565b6001600160a01b0381166109d65760405162461bcd60e51b8152600401808060200182810382526022815260200180610cfb6022913960400191505060405180910390fd5b6109e8816001600160a01b0316610c0f565b610a39576040805162461bcd60e51b815260206004820152601760248201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604482015290519081900360640190fd5b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b6000610a6b83836108c7565b610aa1575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556104cb565b5060006104cb565b60008181526001830160205260408120548015610b655783546000198083019190810190600090879083908110610adc57fe5b9060005260206000200154905080876000018481548110610af957fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080610b2957fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506104cb565b60009150506104cb565b600054610100900460ff1680610b885750610b8861077f565b80610b96575060005460ff16155b610bd15760405162461bcd60e51b815260040180806020018281038252602e815260200180610ccd602e913960400191505060405180910390fd5b600054610100900460ff1615801561097c576000805460ff1961ff001990911661010017166001179055801561098e576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590610c4357508115155b94935050505056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e6473416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e74416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b65436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a6564436f6e74726163744d616e616765722061646472657373206973206e6f7420736574416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c66a2646970667358221220a8219aa9a2a78cfbe5c2c5011d52370c1d2df07290f28cea29685bd160d742f764736f6c634300060a0033
[ 4, 7, 9, 6, 10 ]
0x4c412F365F2Cea503BC0D519a48E54670D6fd729
pragma solidity 0.6.12; 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); } } } } 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; } } 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)); } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract MINTER is ERC20 ('MINTER', 'MINTER'), Ownable { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private minters; function adminAllowMinter (address _address, bool _allow) public onlyOwner { if (_allow) { minters.add(_address); } else { minters.remove(_address); } } modifier onlyMinter() { require(minters.contains(msg.sender), "MINTER: caller is not the minter"); _; } /// @notice Creates `_amount` token to `_to`. function mint(address _to, uint256 _amount) public onlyMinter { _mint(_to, _amount); } function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } function mintersLength() external view returns (uint256) { return minters.length(); } function minterAtIndex(uint256 _index) external view returns (address) { return minters.at(_index); } }
0x608060405234801561001057600080fd5b50600436106101215760003560e01c806370a08231116100ad578063a9059cbb11610071578063a9059cbb1461057d578063c37bbabc146105e1578063c7585ed1146105ff578063dd62ed3e14610657578063f2fde38b146106cf57610121565b806370a0823114610400578063715018a6146104585780638da5cb5b1461046257806395d89b4114610496578063a457c2d71461051957610121565b8063313ce567116100f4578063313ce567146102af57806339509351146102d05780633a1366471461033457806340c10f191461038457806342966c68146103d257610121565b806306fdde0314610126578063095ea7b3146101a957806318160ddd1461020d57806323b872dd1461022b575b600080fd5b61012e610713565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561016e578082015181840152602081019050610153565b50505050905090810190601f16801561019b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101f5600480360360408110156101bf57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506107b5565b60405180821515815260200191505060405180910390f35b6102156107d3565b6040518082815260200191505060405180910390f35b6102976004803603606081101561024157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506107dd565b60405180821515815260200191505060405180910390f35b6102b76108b6565b604051808260ff16815260200191505060405180910390f35b61031c600480360360408110156102e657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506108cd565b60405180821515815260200191505060405180910390f35b6103826004803603604081101561034a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803515159060200190929190505050610980565b005b6103d06004803603604081101561039a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610a84565b005b6103fe600480360360208110156103e857600080fd5b8101908080359060200190929190505050610b18565b005b6104426004803603602081101561041657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610b2c565b6040518082815260200191505060405180910390f35b610460610b74565b005b61046a610cff565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61049e610d29565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156104de5780820151818401526020810190506104c3565b50505050905090810190601f16801561050b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6105656004803603604081101561052f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610dcb565b60405180821515815260200191505060405180910390f35b6105c96004803603604081101561059357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610e98565b60405180821515815260200191505060405180910390f35b6105e9610eb6565b6040518082815260200191505060405180910390f35b61062b6004803603602081101561061557600080fd5b8101908080359060200190929190505050610ec7565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6106b96004803603604081101561066d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ee4565b6040518082815260200191505060405180910390f35b610711600480360360208110156106e557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610f6b565b005b606060038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156107ab5780601f10610780576101008083540402835291602001916107ab565b820191906000526020600020905b81548152906001019060200180831161078e57829003601f168201915b5050505050905090565b60006107c96107c261117b565b8484611183565b6001905092915050565b6000600254905090565b60006107ea84848461137a565b6108ab846107f661117b565b6108a685604051806060016040528060288152602001611f0160289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061085c61117b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461163b9092919063ffffffff16565b611183565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006109766108da61117b565b8461097185600160006108eb61117b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546116fb90919063ffffffff16565b611183565b6001905092915050565b61098861117b565b73ffffffffffffffffffffffffffffffffffffffff16600560019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610a4a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b8015610a6a57610a6482600661178390919063ffffffff16565b50610a80565b610a7e8260066117b390919063ffffffff16565b505b5050565b610a983360066117e390919063ffffffff16565b610b0a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4d494e5445523a2063616c6c6572206973206e6f7420746865206d696e74657281525060200191505060405180910390fd5b610b148282611813565b5050565b610b29610b2361117b565b826119da565b50565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b610b7c61117b565b73ffffffffffffffffffffffffffffffffffffffff16600560019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610c3e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff16600560019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a36000600560016101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b6000600560019054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b606060048054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610dc15780601f10610d9657610100808354040283529160200191610dc1565b820191906000526020600020905b815481529060010190602001808311610da457829003601f168201915b5050505050905090565b6000610e8e610dd861117b565b84610e8985604051806060016040528060258152602001611f936025913960016000610e0261117b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461163b9092919063ffffffff16565b611183565b6001905092915050565b6000610eac610ea561117b565b848461137a565b6001905092915050565b6000610ec26006611b9e565b905090565b6000610edd826006611bb390919063ffffffff16565b9050919050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b610f7361117b565b73ffffffffffffffffffffffffffffffffffffffff16600560019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611035576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156110bb576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180611e936026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff16600560019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a380600560016101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611209576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180611f6f6024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16141561128f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180611eb96022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611400576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180611f4a6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611486576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180611e4e6023913960400191505060405180910390fd5b611491838383611bcd565b6114fc81604051806060016040528060268152602001611edb602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461163b9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061158f816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546116fb90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b60008383111582906116e8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156116ad578082015181840152602081019050611692565b50505050905090810190601f1680156116da5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015611779576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b60006117ab836000018373ffffffffffffffffffffffffffffffffffffffff1660001b611bd2565b905092915050565b60006117db836000018373ffffffffffffffffffffffffffffffffffffffff1660001b611c42565b905092915050565b600061180b836000018373ffffffffffffffffffffffffffffffffffffffff1660001b611d2a565b905092915050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156118b6576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45524332303a206d696e7420746f20746865207a65726f20616464726573730081525060200191505060405180910390fd5b6118c260008383611bcd565b6118d7816002546116fb90919063ffffffff16565b60028190555061192e816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546116fb90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611a60576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180611f296021913960400191505060405180910390fd5b611a6c82600083611bcd565b611ad781604051806060016040528060228152602001611e71602291396000808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461163b9092919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611b2e81600254611d4d90919063ffffffff16565b600281905550600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b6000611bac82600001611d97565b9050919050565b6000611bc28360000183611da8565b60001c905092915050565b505050565b6000611bde8383611d2a565b611c37578260000182908060018154018082558091505060019003906000526020600020016000909190919091505582600001805490508360010160008481526020019081526020016000208190555060019050611c3c565b600090505b92915050565b60008083600101600084815260200190815260200160002054905060008114611d1e5760006001820390506000600186600001805490500390506000866000018281548110611c8d57fe5b9060005260206000200154905080876000018481548110611caa57fe5b9060005260206000200181905550600183018760010160008381526020019081526020016000208190555086600001805480611ce257fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050611d24565b60009150505b92915050565b600080836001016000848152602001908152602001600020541415905092915050565b6000611d8f83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061163b565b905092915050565b600081600001805490509050919050565b600081836000018054905011611e09576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180611e2c6022913960400191505060405180910390fd5b826000018281548110611e1857fe5b906000526020600020015490509291505056fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e647345524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e63654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220fecedc5ed62ecfe3ef8dc26570703ac12075a61a0fab5115595f7debda5d75f664736f6c634300060c0033
[ 5 ]
0x4d64ab5893659451d80b20dab9d610ad2fb40579
pragma solidity 0.6.8; 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 vaults 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract CryptoPunksMarket { address owner; string public standard = "CryptoPunks"; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public nextPunkIndexToAssign = 0; bool public allPunksAssigned = false; uint256 public punksRemainingToAssign = 0; //mapping (address => uint) public addressToPunkIndex; mapping(uint256 => address) public punkIndexToAddress; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } // A record of punks that are offered for sale at a specific minimum value, and perhaps to a specific person mapping(uint256 => Offer) public punksOfferedForSale; // A record of the highest punk bid mapping(uint256 => Bid) public punkBids; mapping(address => uint256) public pendingWithdrawals; event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public payable { // balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens owner = msg.sender; totalSupply = 10000; // Update total supply punksRemainingToAssign = totalSupply; name = "CRYPTOPUNKS"; // Set the name for display purposes symbol = "Ͼ"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes } function setInitialOwner(address to, uint256 punkIndex) public { // require(msg.sender == owner, "msg.sender != owner"); require(!allPunksAssigned); require(punkIndex < 10000); if (punkIndexToAddress[punkIndex] != to) { if (punkIndexToAddress[punkIndex] != address(0)) { balanceOf[punkIndexToAddress[punkIndex]]--; } else { punksRemainingToAssign--; } punkIndexToAddress[punkIndex] = to; balanceOf[to]++; emit PunkTransfer(address(0), to, punkIndex); } } function setInitialOwners( address[] memory addresses, uint256[] memory indices ) public { require(msg.sender == owner); uint256 n = addresses.length; for (uint256 i = 0; i < n; i++) { setInitialOwner(addresses[i], indices[i]); } } function allInitialOwnersAssigned() public { require(msg.sender == owner); allPunksAssigned = true; } function getPunk(uint256 punkIndex) public { // require(allPunksAssigned); require(punksRemainingToAssign != 0); require(punkIndexToAddress[punkIndex] == address(0)); require(punkIndex < 10000); punkIndexToAddress[punkIndex] = msg.sender; balanceOf[msg.sender]++; punksRemainingToAssign--; emit Assign(msg.sender, punkIndex); } // Transfer ownership of a punk to another user without requiring payment function transferPunk(address to, uint256 punkIndex) public { // // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); if (punksOfferedForSale[punkIndex].isForSale) { punkNoLongerForSale(punkIndex); } punkIndexToAddress[punkIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; emit Transfer(msg.sender, to, 1); emit PunkTransfer(msg.sender, to, punkIndex); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == to) { // Kill bid and revault value pendingWithdrawals[to] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function punkNoLongerForSale(uint256 punkIndex) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, msg.sender, 0, address(0) ); emit PunkNoLongerForSale(punkIndex); } function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, address(0) ); emit PunkOffered(punkIndex, minSalePriceInWei, address(0)); } function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, toAddress ); emit PunkOffered(punkIndex, minSalePriceInWei, toAddress); } function buyPunk(uint256 punkIndex) public payable { // require(allPunksAssigned); Offer storage offer = punksOfferedForSale[punkIndex]; require(punkIndex < 10000); require(offer.isForSale); // punk not actually for sale (offer.onlySellTo == address(0) || offer.onlySellTo == msg.sender); // punk not supposed to be sold to this user require(msg.value >= offer.minValue); // Didn't send enough ETH require(offer.seller == punkIndexToAddress[punkIndex]); // Seller no longer owner of punk address seller = offer.seller; punkIndexToAddress[punkIndex] = msg.sender; balanceOf[seller]--; balanceOf[msg.sender]++; emit Transfer(seller, msg.sender, 1); punkNoLongerForSale(punkIndex); pendingWithdrawals[seller] += msg.value; emit PunkBought(punkIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == msg.sender) { // Kill bid and revault value pendingWithdrawals[msg.sender] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function withdraw() public { // require(allPunksAssigned); uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending revault before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } function enterBidForPunk(uint256 punkIndex) public payable { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); require(msg.value != 0); Bid storage existing = punkBids[punkIndex]; require(msg.value > existing.value); if (existing.value > 0) { // Revault the failing bid pendingWithdrawals[existing.bidder] += existing.value; } punkBids[punkIndex] = Bid(true, punkIndex, msg.sender, msg.value); emit PunkBidEntered(punkIndex, msg.value, msg.sender); } function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); address seller = msg.sender; Bid storage bid = punkBids[punkIndex]; require(bid.value != 0); require(bid.value >= minPrice); punkIndexToAddress[punkIndex] = bid.bidder; balanceOf[seller]--; balanceOf[bid.bidder]++; emit Transfer(seller, bid.bidder, 1); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, bid.bidder, 0, address(0) ); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); pendingWithdrawals[seller] += amount; emit PunkBought(punkIndex, bid.value, seller, bid.bidder); } function withdrawBidForPunk(uint256 punkIndex) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); Bid storage bid = punkBids[punkIndex]; require(bid.bidder == msg.sender); emit PunkBidWithdrawn(punkIndex, bid.value, msg.sender); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); // Revault the bid money msg.sender.transfer(amount); } } 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)); } } interface ICryptoPunksMarket { struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; address onlySellTo; } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); function setInitialOwner(address to, uint256 punkIndex) external; function setInitialOwners( address[] calldata addresses, uint256[] calldata indices ) external; function allInitialOwnersAssigned() external; function getPunk(uint256 punkIndex) external; function transferPunk(address to, uint256 punkIndex) external; function punkNoLongerForSale(uint256 punkIndex) external; function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) external; function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) external; function buyPunk(uint256 punkIndex) external; function withdraw() external; function enterBidForPunk(uint256 punkIndex) external; function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) external; function withdrawBidForPunk(uint256 punkIndex) external; function punkIndexToAddress(uint256 punkIndex) external returns (address); function punksOfferedForSale(uint256 punkIndex) external returns ( bool isForSale, uint256 _punkIndex, address seller, uint256 minValue, address onlySellTo ); function balanceOf(address user) external returns (uint256); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IXToken is IERC20 { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function mint(address to, uint256 amount) external; function changeName(string calldata name) external; function changeSymbol(string calldata symbol) external; function setVaultAddress(address vaultAddress) external; } 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; } } contract Pausable is Ownable { bool private isPaused = false; event Paused(); event Unpaused(); function getIsPaused() public view returns (bool) { return isPaused; } function pause() public onlyOwner { isPaused = true; } function unpause() public onlyOwner { isPaused = false; } modifier whenPaused { require(isPaused, "Contract is not paused"); _; } modifier whenNotPaused { require(!isPaused, "Contract is paused"); _; } } 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 revault on every call to nonReentrant will be lower in // amount. Since revaults 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 revault 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 revault is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract XVaultBase is Pausable { address private erc20Address; address private cpmAddress; IXToken private erc20; ICryptoPunksMarket private cpm; function getERC20Address() public view returns (address) { return erc20Address; } function getCpmAddress() public view returns (address) { return cpmAddress; } function getERC20() internal view returns (IXToken) { return erc20; } function getCPM() internal view returns (ICryptoPunksMarket) { return cpm; } function setERC20Address(address newAddress) internal { require(erc20Address == address(0), "Already initialized ERC20"); erc20Address = newAddress; erc20 = IXToken(erc20Address); } function setCpmAddress(address newAddress) internal { require(cpmAddress == address(0), "Already initialized CPM"); cpmAddress = newAddress; cpm = ICryptoPunksMarket(cpmAddress); } } contract XVaultSafe is XVaultBase, ReentrancyGuard { using EnumerableSet for EnumerableSet.UintSet; EnumerableSet.UintSet private reserves; bool private inSafeMode = true; event TokenBurnedSafely(uint256 punkId, address indexed to); function getReserves() internal view returns (EnumerableSet.UintSet storage) { return reserves; } function getInSafeMode() public view returns (bool) { return inSafeMode; } function turnOffSafeMode() public onlyOwner { inSafeMode = false; } function turnOnSafeMode() public onlyOwner { inSafeMode = true; } modifier whenNotInSafeMode { require(!inSafeMode, "Contract is in safe mode"); _; } function simpleRedeem() public whenPaused nonReentrant { require( getERC20().balanceOf(msg.sender) >= 10**18, "ERC20 balance too small" ); require( getERC20().allowance(msg.sender, address(this)) >= 10**18, "ERC20 allowance too small" ); uint256 tokenId = reserves.at(0); getERC20().burnFrom(msg.sender, 10**18); reserves.remove(tokenId); getCPM().transferPunk(msg.sender, tokenId); emit TokenBurnedSafely(tokenId, msg.sender); } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _changeName(string memory name_) internal { _name = name_; } function _changeSymbol(string memory symbol_) internal { _symbol = symbol_; } /** * @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 {} } abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } contract Timelocked is XVaultSafe { using SafeMath for uint256; enum Timelock {Short, Medium, Long} uint256 private securityLevel; function getSecurityLevel() public view returns (string memory) { if (securityLevel == 0) { return "red"; } else if (securityLevel == 1) { return "orange"; } else if (securityLevel == 2) { return "yellow"; } else { return "green"; } } function increaseSecurityLevel() public onlyOwner { require(securityLevel < 3, "Already max"); securityLevel = securityLevel + 1; } function timeInDays(uint256 num) internal pure returns (uint256) { return num * 60 * 60 * 24; } function getDelay(Timelock lockId) public view returns (uint256) { if (securityLevel == 0) { return 2; // for testing } if (lockId == Timelock.Short) { if (securityLevel == 1) { return timeInDays(1); } else if (securityLevel == 2) { return timeInDays(2); } else { return timeInDays(3); } } else if (lockId == Timelock.Medium) { if (securityLevel == 1) { return timeInDays(2); } else if (securityLevel == 2) { return timeInDays(3); } else { return timeInDays(5); } } else { if (securityLevel == 1) { return timeInDays(3); } else if (securityLevel == 2) { return timeInDays(5); } else { return timeInDays(10); } } } mapping(Timelock => uint256) private releaseTimes; event Locked(Timelock lockId); event UnlockInitiated(Timelock lockId, uint256 whenUnlocked); function getReleaseTime(Timelock lockId) public view returns (uint256) { return releaseTimes[lockId]; } function initiateUnlock(Timelock lockId) public onlyOwner { uint256 newReleaseTime = now.add(getDelay(lockId)); releaseTimes[lockId] = newReleaseTime; emit UnlockInitiated(lockId, newReleaseTime); } function lock(Timelock lockId) public onlyOwner { releaseTimes[lockId] = 0; emit Locked(lockId); } modifier whenNotLockedS { uint256 releaseTime = releaseTimes[Timelock.Short]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedM { uint256 releaseTime = releaseTimes[Timelock.Medium]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedL { uint256 releaseTime = releaseTimes[Timelock.Long]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } } contract XToken is Context, Ownable, ERC20Burnable { address private vaultAddress; constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _mint(msg.sender, 0); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function changeName(string memory name) public onlyOwner { _changeName(name); } function changeSymbol(string memory symbol) public onlyOwner { _changeSymbol(symbol); } function getVaultAddress() public view returns (address) { return vaultAddress; } function setVaultAddress(address newAddress) public onlyOwner { vaultAddress = newAddress; } } contract Profitable is Timelocked { mapping(address => bool) private verifiedIntegrators; uint256 private numIntegrators = 0; uint256[] private mintFees = [0, 0, 0]; uint256[] private burnFees = [0, 0, 0, (5 * 10**18), 20]; uint256[] private dualFees = [0, 0, 0]; event MintFeesSet(uint256[] mintFees); event BurnFeesSet(uint256[] burnFees); event DualFeesSet(uint256[] dualFees); event IntegratorSet(address account, bool isVerified); event Withdrawal(address to, uint256 amount); function getMintFees() public view returns (uint256[] memory) { return mintFees; } function getBurnFees() public view returns (uint256[] memory) { return burnFees; } function getDualFees() public view returns (uint256[] memory) { return dualFees; } function _getMintFees() internal view returns (uint256[] storage) { return mintFees; } function _getBurnFees() internal view returns (uint256[] storage) { return burnFees; } function _getDualFees() internal view returns (uint256[] storage) { return dualFees; } function setMintFees(uint256[] memory newMintFees) public onlyOwner whenNotLockedM { require(newMintFees.length == 3, "Wrong length"); mintFees = newMintFees; emit MintFeesSet(newMintFees); } function setBurnFees(uint256[] memory newBurnFees) public onlyOwner whenNotLockedL { require(newBurnFees.length == 5, "Wrong length"); burnFees = newBurnFees; emit BurnFeesSet(newBurnFees); } function setDualFees(uint256[] memory newDualFees) public onlyOwner whenNotLockedM { require(newDualFees.length == 3, "Wrong length"); dualFees = newDualFees; emit DualFeesSet(newDualFees); } function isIntegrator(address account) public view returns (bool) { return verifiedIntegrators[account]; } function getNumIntegrators() public view returns (uint256) { return numIntegrators; } function setIntegrator(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedIntegrators[account], "Already set"); if (isVerified) { numIntegrators = numIntegrators.add(1); } else { numIntegrators = numIntegrators.sub(1); } verifiedIntegrators[account] = isVerified; emit IntegratorSet(account, isVerified); } function getFee(address account, uint256 numTokens, uint256[] storage fees) internal view returns (uint256) { uint256 fee = 0; if (verifiedIntegrators[account]) { return 0; } else if (numTokens == 1) { fee = fees[0]; } else { fee = fees[1] + numTokens * fees[2]; } // if this is a burn operation... if (fees.length > 3) { // if reserves are low... uint256 reservesLength = getReserves().length(); uint256 padding = fees[4]; if (reservesLength - numTokens <= padding) { uint256 addedFee = 0; for (uint256 i = 0; i < numTokens; i++) { if ( reservesLength - i <= padding && reservesLength - i > 0 ) { addedFee += (fees[3] * (padding - (reservesLength - i) + 1)); } } fee += addedFee; } } return fee; } function withdraw(address payable to) public onlyOwner whenNotLockedM { uint256 balance = address(this).balance; to.transfer(balance); emit Withdrawal(to, balance); } } contract Controllable is Profitable { mapping(address => bool) private verifiedControllers; uint256 private numControllers = 0; event ControllerSet(address account, bool isVerified); event DirectRedemption(uint256 punkId, address by, address indexed to); function isController(address account) public view returns (bool) { return verifiedControllers[account]; } function getNumControllers() public view returns (uint256) { return numControllers; } function setController(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedControllers[account], "Already set"); if (isVerified) { numControllers++; } else { numControllers--; } verifiedControllers[account] = isVerified; emit ControllerSet(account, isVerified); } modifier onlyController() { require(isController(_msgSender()), "Not a controller"); _; } function directRedeem(uint256 tokenId, address to) public onlyController { require(getERC20().balanceOf(to) >= 10**18, "ERC20 balance too small"); bool toSelf = (to == address(this)); require( toSelf || (getERC20().allowance(to, address(this)) >= 10**18), "ERC20 allowance too small" ); require(getReserves().contains(tokenId), "Not in holdings"); getERC20().burnFrom(to, 10**18); getReserves().remove(tokenId); if (!toSelf) { getCPM().transferPunk(to, tokenId); } emit DirectRedemption(tokenId, _msgSender(), to); } } contract Randomizable is Controllable { uint256 private randNonce = 0; function getPseudoRand(uint256 modulus) internal returns (uint256) { randNonce = randNonce.add(1); return uint256(keccak256(abi.encodePacked(now, _msgSender(), randNonce))) % modulus; } } contract Manageable is Randomizable { event MigrationComplete(address to); event TokenNameChange(string name); event TokenSymbolChange(string symbol); function migrate(address to) public onlyOwner whenNotLockedL { uint256 reservesLength = getReserves().length(); for (uint256 i = 0; i < reservesLength; i++) { uint256 tokenId = getReserves().at(i); getCPM().transferPunk(to, tokenId); } emit MigrationComplete(to); } function changeTokenName(string memory newName) public onlyOwner whenNotLockedM { getERC20().changeName(newName); emit TokenNameChange(newName); } function changeTokenSymbol(string memory newSymbol) public onlyOwner whenNotLockedM { getERC20().changeSymbol(newSymbol); emit TokenSymbolChange(newSymbol); } function setReverseLink() public onlyOwner whenNotLockedS { getERC20().setVaultAddress(address(this)); } } contract XVault is Manageable { event TokenMinted(uint256 tokenId, address indexed to); event TokensMinted(uint256[] tokenIds, address indexed to); event TokenBurned(uint256 tokenId, address indexed to); event TokensBurned(uint256[] tokenIds, address indexed to); constructor(address erc20Address, address cpmAddress) public { setERC20Address(erc20Address); setCpmAddress(cpmAddress); } function getCryptoPunkAtIndex(uint256 index) public view returns (uint256) { return getReserves().at(index); } function getReservesLength() public view returns (uint256) { return getReserves().length(); } function isCryptoPunkDeposited(uint256 tokenId) public view returns (bool) { return getReserves().contains(tokenId); } function mintPunk(uint256 tokenId) public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getMintFees()); require(msg.value >= fee, "Value too low"); _mintPunk(tokenId, false); } function _mintPunk(uint256 tokenId, bool partOfDualOp) private returns (bool) { address msgSender = _msgSender(); require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); require(_tokenId == tokenId, "Wrong punk"); require(forSale, "Punk not available"); require(buyer == address(this), "Transfer not approved"); require(minVal == 0, "Min value not zero"); require(msgSender == seller, "Sender is not seller"); require( msgSender == getCPM().punkIndexToAddress(tokenId), "Sender is not owner" ); getCPM().buyPunk(tokenId); getReserves().add(tokenId); if (!partOfDualOp) { uint256 tokenAmount = 10**18; getERC20().mint(msgSender, tokenAmount); } emit TokenMinted(tokenId, _msgSender()); return true; } function mintPunkMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), tokenIds.length, _getMintFees()); require(msg.value >= fee, "Value too low"); _mintPunkMultiple(tokenIds, false); } function _mintPunkMultiple(uint256[] memory tokenIds, bool partOfDualOp) private returns (uint256) { require(tokenIds.length > 0, "No tokens"); require(tokenIds.length <= 100, "Over 100 tokens"); uint256[] memory newTokenIds = new uint256[](tokenIds.length); uint256 numNewTokens = 0; address msgSender = _msgSender(); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); bool rightToken = _tokenId == tokenId; bool isApproved = buyer == address(this); bool priceIsZero = minVal == 0; bool isSeller = msgSender == seller; bool isOwner = msgSender == getCPM().punkIndexToAddress(tokenId); if ( forSale && rightToken && isApproved && priceIsZero && isSeller && isOwner ) { getCPM().buyPunk(tokenId); getReserves().add(tokenId); newTokenIds[numNewTokens] = tokenId; numNewTokens = numNewTokens.add(1); } } if (numNewTokens > 0) { if (!partOfDualOp) { uint256 tokenAmount = numNewTokens * (10**18); getERC20().mint(msgSender, tokenAmount); } emit TokensMinted(newTokenIds, msgSender); } return numNewTokens; } function redeemPunk() public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getBurnFees()); require(msg.value >= fee, "Value too low"); _redeemPunk(false); } function _redeemPunk(bool partOfDualOp) private { address msgSender = _msgSender(); uint256 tokenAmount = 10**18; require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); emit TokenBurned(tokenId, msgSender); } function redeemPunkMultiple(uint256 numTokens) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), numTokens, _getBurnFees()); require(msg.value >= fee, "Value too low"); _redeemPunkMultiple(numTokens, false); } function _redeemPunkMultiple(uint256 numTokens, bool partOfDualOp) private { require(numTokens > 0, "No tokens"); require(numTokens <= 100, "Over 100 tokens"); address msgSender = _msgSender(); uint256 tokenAmount = numTokens * (10**18); require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } uint256[] memory tokenIds = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); tokenIds[i] = tokenId; getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); } emit TokensBurned(tokenIds, msgSender); } function mintAndRedeem(uint256 tokenId) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), 1, _getDualFees()); require(msg.value >= fee, "Value too low"); require(_mintPunk(tokenId, true), "Minting failed"); _redeemPunk(true); } function mintAndRedeemMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 numTokens = tokenIds.length; require(numTokens > 0, "No tokens"); require(numTokens <= 20, "Over 20 tokens"); uint256 fee = getFee(_msgSender(), numTokens, _getDualFees()); require(msg.value >= fee, "Value too low"); uint256 numTokensMinted = _mintPunkMultiple(tokenIds, true); if (numTokensMinted > 0) { _redeemPunkMultiple(numTokens, true); } } function mintRetroactively(uint256 tokenId, address to) public onlyOwner whenNotLockedS { require( getCPM().punkIndexToAddress(tokenId) == address(this), "Not owner" ); require(!getReserves().contains(tokenId), "Already in reserves"); uint256 cryptoPunkBalance = getCPM().balanceOf(address(this)); require( (getERC20().totalSupply() / (10**18)) < cryptoPunkBalance, "No excess NFTs" ); getReserves().add(tokenId); getERC20().mint(to, 10**18); emit TokenMinted(tokenId, _msgSender()); } function redeemRetroactively(address to) public onlyOwner whenNotLockedS { require( getERC20().balanceOf(address(this)) >= (10**18), "Not enough PUNK" ); getERC20().burn(10**18); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); getReserves().remove(tokenId); getCPM().transferPunk(to, tokenId); emit TokenBurned(tokenId, _msgSender()); } }
0x6080604052600436106102885760003560e01c806397a6d2741161015a578063cf43cd6d116100c1578063f2fde38b1161007a578063f2fde38b14610c1c578063f338fc1914610c4f578063fa70c30214610c64578063fb15298d14610cee578063fb34499d14610d27578063fc9d015414610d5457610288565b8063cf43cd6d14610a2d578063cf97174814610adb578063e0dba60f14610b7c578063e63b094014610bb7578063f055c9a014610bcc578063f2a6f21514610c0757610288565b8063b429afeb11610113578063b429afeb1461083e578063b9f890de14610871578063c2c0d41814610886578063c6d3ab9d1461089b578063c73cce391461094c578063ce5494bb146109fa57610288565b806397a6d274146106e65780639f3d4e69146107195780639f92b09b14610746578063a2be5a1f14610770578063a70e81fd14610778578063b0018bfc1461078d57610288565b8063715018a6116101fe578063830ddb97116101b7578063830ddb971461058d5780638456cb59146105aa57806386a206e4146105bf5780638985a3f0146105f057806389caf16d1461069e5780638da5cb5b146106d157610288565b8063715018a6146104b757806372e0dbd4146104cc57806372f9c421146104e95780637af9bc02146105165780637fc72e751461052b578063824580b31461055457610288565b80633e8354f0116102505780633e8354f0146104135780633f4ba83a146104285780634ad4f87c1461043d57806351cff8d9146104525780635395b702146104855780635ea0fa041461049a57610288565b80630bdf02bd1461028d5780632361741e146102cc5780632753167b1461033157806331f8a39d1461034657806334d9d89c146103e9575b600080fd5b34801561029957600080fd5b506102ba600480360360208110156102b057600080fd5b503560ff16610d69565b60408051918252519081900360200190f35b3480156102d857600080fd5b506102e1610d9d565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561031d578181015183820152602001610305565b505050509050019250505060405180910390f35b34801561033d57600080fd5b506102e1610df6565b6103e76004803603602081101561035c57600080fd5b810190602081018135600160201b81111561037657600080fd5b82018360208201111561038857600080fd5b803590602001918460208302840111600160201b831117156103a957600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550610e4c945050505050565b005b3480156103f557600080fd5b506102ba6004803603602081101561040c57600080fd5b5035610fb6565b34801561041f57600080fd5b506103e7610fd6565b34801561043457600080fd5b506103e761107e565b34801561044957600080fd5b506102ba6110e5565b34801561045e57600080fd5b506103e76004803603602081101561047557600080fd5b50356001600160a01b03166110eb565b34801561049157600080fd5b506102ba61125d565b6103e7600480360360208110156104b057600080fd5b5035611263565b3480156104c357600080fd5b506103e7611413565b6103e7600480360360208110156104e257600080fd5b50356114b5565b3480156104f557600080fd5b506102ba6004803603602081101561050c57600080fd5b503560ff1661160f565b34801561052257600080fd5b506103e76116ef565b34801561053757600080fd5b50610540611aaa565b604080519115158252519081900360200190f35b34801561056057600080fd5b506103e76004803603604081101561057757600080fd5b50803590602001356001600160a01b0316611ab3565b6103e7600480360360208110156105a357600080fd5b5035611eb0565b3480156105b657600080fd5b506103e7611fb8565b3480156105cb57600080fd5b506105d4612025565b604080516001600160a01b039092168252519081900360200190f35b3480156105fc57600080fd5b506103e76004803603602081101561061357600080fd5b810190602081018135600160201b81111561062d57600080fd5b82018360208201111561063f57600080fd5b803590602001918460208302840111600160201b8311171561066057600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612034945050505050565b3480156106aa57600080fd5b506103e7600480360360208110156106c157600080fd5b50356001600160a01b03166121f6565b3480156106dd57600080fd5b506105d4612547565b3480156106f257600080fd5b506105406004803603602081101561070957600080fd5b50356001600160a01b0316612556565b34801561072557600080fd5b506103e76004803603602081101561073c57600080fd5b503560ff16612574565b34801561075257600080fd5b506105406004803603602081101561076957600080fd5b5035612643565b6103e7612651565b34801561078457600080fd5b506103e7612760565b34801561079957600080fd5b506103e7600480360360208110156107b057600080fd5b810190602081018135600160201b8111156107ca57600080fd5b8201836020820111156107dc57600080fd5b803590602001918460018302840111600160201b831117156107fd57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295506128db945050505050565b34801561084a57600080fd5b506105406004803603602081101561086157600080fd5b50356001600160a01b0316612b2f565b34801561087d57600080fd5b506105d4612b4d565b34801561089257600080fd5b506102ba612b5c565b3480156108a757600080fd5b506103e7600480360360208110156108be57600080fd5b810190602081018135600160201b8111156108d857600080fd5b8201836020820111156108ea57600080fd5b803590602001918460018302840111600160201b8311171561090b57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612b6e945050505050565b34801561095857600080fd5b506103e76004803603602081101561096f57600080fd5b810190602081018135600160201b81111561098957600080fd5b82018360208201111561099b57600080fd5b803590602001918460208302840111600160201b831117156109bc57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612d80945050505050565b348015610a0657600080fd5b506103e760048036036020811015610a1d57600080fd5b50356001600160a01b0316612f25565b348015610a3957600080fd5b506103e760048036036020811015610a5057600080fd5b810190602081018135600160201b811115610a6a57600080fd5b820183602082011115610a7c57600080fd5b803590602001918460208302840111600160201b83111715610a9d57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061311f945050505050565b6103e760048036036020811015610af157600080fd5b810190602081018135600160201b811115610b0b57600080fd5b820183602082011115610b1d57600080fd5b803590602001918460208302840111600160201b83111715610b3e57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506132d6945050505050565b348015610b8857600080fd5b506103e760048036036040811015610b9f57600080fd5b506001600160a01b03813516906020013515156134d7565b348015610bc357600080fd5b506103e76136ad565b348015610bd857600080fd5b506103e760048036036040811015610bef57600080fd5b506001600160a01b0381351690602001351515613711565b348015610c1357600080fd5b50610540613902565b348015610c2857600080fd5b506103e760048036036020811015610c3f57600080fd5b50356001600160a01b0316613912565b348015610c5b57600080fd5b506102e1613a0a565b348015610c7057600080fd5b50610c79613a60565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610cb3578181015183820152602001610c9b565b50505050905090810190601f168015610ce05780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610cfa57600080fd5b506103e760048036036040811015610d1157600080fd5b50803590602001356001600160a01b0316613b0b565b348015610d3357600080fd5b506103e760048036036020811015610d4a57600080fd5b503560ff16613f5f565b348015610d6057600080fd5b506103e7614053565b6000600a6000836002811115610d7b57fe5b6002811115610d8657fe5b81526020019081526020016000205490505b919050565b6060600e805480602002602001604051908101604052809291908181526020018280548015610deb57602002820191906000526020600020905b815481526020019060010190808311610dd7575b505050505090505b90565b6060600f805480602002602001604051908101604052809291908181526020018280548015610deb5760200282019190600052602060002090815481526020019060010190808311610dd7575050505050905090565b60026005541415610e92576040805162461bcd60e51b815260206004820152601f602482015260008051602061575f833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615610eeb576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff1615610f3e576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b6000610f5a610f4b6140ba565b8351610f556140be565b6140c3565b905080341015610fa1576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b610fac8260006141f3565b5050600160055550565b6000610fd082610fc4614693565b9063ffffffff61469816565b92915050565b610fde6140ba565b6000546001600160a01b0390811691161461102e576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b600360095410611073576040805162461bcd60e51b815260206004820152600b60248201526a082d8e4cac2c8f240dac2f60ab1b604482015290519081900360640190fd5b600980546001019055565b6110866140ba565b6000546001600160a01b039081169116146110d6576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6000805460ff60a01b19169055565b600c5490565b6110f36140ba565b6000546001600160a01b03908116911614611143576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600052600a6020526000805160206157c58339815191525480611198576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116111db576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b60405147906001600160a01b0384169082156108fc029083906000818181858888f19350505050158015611213573d6000803e3d6000fd5b50604080516001600160a01b03851681526020810183905281517f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65929181900390910190a1505050565b60115490565b600260055414156112a9576040805162461bcd60e51b815260206004820152601f602482015260008051602061575f833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615611302576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff1615611355576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b600061136c6113626140ba565b6001610f556146a4565b9050803410156113b3576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b6113be8260016146a9565b611400576040805162461bcd60e51b815260206004820152600e60248201526d135a5b9d1a5b99c819985a5b195960921b604482015290519081900360640190fd5b61140a6001614b4b565b50506001600555565b61141b6140ba565b6000546001600160a01b0390811691161461146b576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b600260055414156114fb576040805162461bcd60e51b815260206004820152601f602482015260008051602061575f833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615611554576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff16156115a7576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b60006115bd6115b46140ba565b83610f55614ea0565b905080341015611604576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b61140a826000614ea5565b60006009546000141561162457506002610d98565b600082600281111561163257fe5b141561167357600954600114156116545761164d600161533e565b9050610d98565b600954600214156116695761164d600261533e565b61164d600361533e565b600182600281111561168157fe5b14156116bb576009546001141561169c5761164d600261533e565b600954600214156116b15761164d600361533e565b61164d600561533e565b600954600114156116d05761164d600361533e565b600954600214156116e55761164d600561533e565b61164d600a61533e565b600054600160a01b900460ff16611746576040805162461bcd60e51b815260206004820152601660248201527510dbdb9d1c9858dd081a5cc81b9bdd081c185d5cd95960521b604482015290519081900360640190fd5b6002600554141561178c576040805162461bcd60e51b815260206004820152601f602482015260008051602061575f833981519152604482015290519081900360640190fd5b6002600555670de0b6b3a76400006117a2615346565b6001600160a01b03166370a08231336040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b1580156117f757600080fd5b505afa15801561180b573d6000803e3d6000fd5b505050506040513d602081101561182157600080fd5b50511015611870576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b670de0b6b3a7640000611881615346565b60408051636eb1769f60e11b815233600482015230602482015290516001600160a01b03929092169163dd62ed3e91604480820192602092909190829003018186803b1580156118d057600080fd5b505afa1580156118e4573d6000803e3d6000fd5b505050506040513d60208110156118fa57600080fd5b5051101561194b576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b600061195e60068263ffffffff61469816565b9050611968615346565b6040805163079cc67960e41b8152336004820152670de0b6b3a7640000602482015290516001600160a01b0392909216916379cc67909160448082019260009290919082900301818387803b1580156119c057600080fd5b505af11580156119d4573d6000803e3d6000fd5b505050506119ec81600661535590919063ffffffff16565b506119f5615361565b6001600160a01b0316638b72a2ec33836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015611a5457600080fd5b505af1158015611a68573d6000803e3d6000fd5b50506040805184815290513393507f8b309647fdd65a5ccf8e22445d08d0c72aca99f0674013717bb2fde8d64709ae92509081900360200190a2506001600555565b60085460ff1690565b611ac3611abe6140ba565b612b2f565b611b07576040805162461bcd60e51b815260206004820152601060248201526f2737ba10309031b7b73a3937b63632b960811b604482015290519081900360640190fd5b670de0b6b3a7640000611b18615346565b6001600160a01b03166370a08231836040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015611b6d57600080fd5b505afa158015611b81573d6000803e3d6000fd5b505050506040513d6020811015611b9757600080fd5b50511015611be6576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b6001600160a01b03811630148080611c8a5750670de0b6b3a7640000611c0a615346565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b158015611c5b57600080fd5b505afa158015611c6f573d6000803e3d6000fd5b505050506040513d6020811015611c8557600080fd5b505110155b611cd7576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b611cef83611ce3614693565b9063ffffffff61537016565b611d32576040805162461bcd60e51b815260206004820152600f60248201526e4e6f7420696e20686f6c64696e677360881b604482015290519081900360640190fd5b611d3a615346565b6001600160a01b03166379cc679083670de0b6b3a76400006040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015611da157600080fd5b505af1158015611db5573d6000803e3d6000fd5b50505050611dd183611dc5614693565b9063ffffffff61535516565b5080611e5757611ddf615361565b6001600160a01b0316638b72a2ec83856040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015611e3e57600080fd5b505af1158015611e52573d6000803e3d6000fd5b505050505b816001600160a01b03167f797bd1463a543a5fb696ff9b9d3340b0bef8762932107d896f055b77e4d93d4b84611e8b6140ba565b604080519283526001600160a01b0390911660208301528051918290030190a2505050565b60026005541415611ef6576040805162461bcd60e51b815260206004820152601f602482015260008051602061575f833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615611f4f576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b6000611f66611f5c6140ba565b6001610f556140be565b905080341015611fad576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b610fac8260006146a9565b611fc06140ba565b6000546001600160a01b03908116911614612010576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6000805460ff60a01b1916600160a01b179055565b6002546001600160a01b031690565b61203c6140ba565b6000546001600160a01b0390811691161461208c576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600052600a6020526000805160206157c583398151915254806120e1576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612124576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600314612169576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b815161217c90600f9060208501906156d7565b507f556290bdbad25e439ee0740de619ad1d21a711a9f3c21030bdaffbfb9b679e15826040518080602001828103825283818151815260200191508051906020019060200280838360005b838110156121df5781810151838201526020016121c7565b505050509050019250505060405180910390a15050565b6121fe6140ba565b6000546001600160a01b0390811691161461224e576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b60008052600a6020527f13da86008ba1c6922daee3e07db95305ef49ebced9f5467a0b8613fcc6b343e354806122b4576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116122f7576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b670de0b6b3a7640000612308615346565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561235d57600080fd5b505afa158015612371573d6000803e3d6000fd5b505050506040513d602081101561238757600080fd5b505110156123ce576040805162461bcd60e51b815260206004820152600f60248201526e4e6f7420656e6f7567682050554e4b60881b604482015290519081900360640190fd5b6123d6615346565b6001600160a01b03166342966c68670de0b6b3a76400006040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b15801561242357600080fd5b505af1158015612437573d6000803e3d6000fd5b50505050600061244d612448614693565b61537c565b9050600061245a82615387565b9050600061246a82610fc4614693565b905061247881611dc5614693565b50612481615361565b6001600160a01b0316638b72a2ec86836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156124e057600080fd5b505af11580156124f4573d6000803e3d6000fd5b505050506125006140ba565b6001600160a01b03167f33631bcd0a4d34a7e2c240ab0753d5adfb7284d8ac89dab6876ec785c0cfa0e6826040518082815260200191505060405180910390a25050505050565b6000546001600160a01b031690565b6001600160a01b03166000908152600b602052604090205460ff1690565b61257c6140ba565b6000546001600160a01b039081169116146125cc576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6000600a60008360028111156125de57fe5b60028111156125e957fe5b8152602001908152602001600020819055507feee8c9a7b7852b972adec4c62096923d399a82270752d09060dd7ad07f39e3f9816040518082600281111561262d57fe5b60ff16815260200191505060405180910390a150565b6000610fd082611ce3614693565b60026005541415612697576040805162461bcd60e51b815260206004820152601f602482015260008051602061575f833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff16156126f0576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60006127076126fd6140ba565b6001610f55614ea0565b90508034101561274e576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b6127586000614b4b565b506001600555565b6127686140ba565b6000546001600160a01b039081169116146127b8576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b60008052600a6020527f13da86008ba1c6922daee3e07db95305ef49ebced9f5467a0b8613fcc6b343e3548061281e576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612861576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b612869615346565b6001600160a01b03166385535cc5306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050600060405180830381600087803b1580156128c057600080fd5b505af11580156128d4573d6000803e3d6000fd5b5050505050565b6128e36140ba565b6000546001600160a01b03908116911614612933576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600052600a6020526000805160206157c58339815191525480612988576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116129cb576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6129d3615346565b6001600160a01b0316635353a2d8836040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015612a2e578181015183820152602001612a16565b50505050905090810190601f168015612a5b5780820380516001836020036101000a031916815260200191505b5092505050600060405180830381600087803b158015612a7a57600080fd5b505af1158015612a8e573d6000803e3d6000fd5b505050507f67c5eb670df7ec2c03a007ee155f462522e530d090c943b70c4eaa5656e0b7c6826040518080602001828103825283818151815260200191508051906020019080838360005b83811015612af1578181015183820152602001612ad9565b50505050905090810190601f168015612b1e5780820380516001836020036101000a031916815260200191505b509250505060405180910390a15050565b6001600160a01b031660009081526010602052604090205460ff1690565b6001546001600160a01b031690565b6000612b69612448614693565b905090565b612b766140ba565b6000546001600160a01b03908116911614612bc6576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600052600a6020526000805160206157c58339815191525480612c1b576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612c5e576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b612c66615346565b6001600160a01b031663a3895fff836040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015612cc1578181015183820152602001612ca9565b50505050905090810190601f168015612cee5780820380516001836020036101000a031916815260200191505b5092505050600060405180830381600087803b158015612d0d57600080fd5b505af1158015612d21573d6000803e3d6000fd5b505060408051602080825286518183015286517f773ec0a6b643b90e0a49ac87584faa630abb0d1fa9bfe5d589918b6e33afbacf9550879450919283929083019185019080838360008315612af1578181015183820152602001612ad9565b612d886140ba565b6000546001600160a01b03908116911614612dd8576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600052600a6020526000805160206157c58339815191525480612e2d576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612e70576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600314612eb5576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b8151612ec890600d9060208501906156d7565b5060408051602080825284518183015284517ff9a8325633515ac20c4c12c09c48b1655bbe4a70f5ac29bd1f85803ef8a3be35938693928392918301918186019102808383600083156121df5781810151838201526020016121c7565b612f2d6140ba565b6000546001600160a01b03908116911614612f7d576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba85480612fe4576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613027576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6000613034612448614693565b905060005b818110156130dd57600061304f82610fc4614693565b9050613059615361565b6001600160a01b0316638b72a2ec86836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156130b857600080fd5b505af11580156130cc573d6000803e3d6000fd5b505060019093019250613039915050565b50604080516001600160a01b038516815290517f6bc1a05a654a49243059be717e63e5e5a88fbb66af7093577daf9a27390722d19181900360200190a1505050565b6131276140ba565b6000546001600160a01b03908116911614613177576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba854806131de576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613221576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600514613266576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b815161327990600e9060208501906156d7565b5060408051602080825284518183015284517fb1aecf0a8e6c83b5d243952384b0db2688bccb20ac76e4ced69a1e13f6a73d2f938693928392918301918186019102808383600083156121df5781810151838201526020016121c7565b6002600554141561331c576040805162461bcd60e51b815260206004820152601f602482015260008051602061575f833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615613375576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff16156133c8576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b805180613408576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b601481111561344f576040805162461bcd60e51b815260206004820152600e60248201526d4f76657220323020746f6b656e7360901b604482015290519081900360640190fd5b600061346561345c6140ba565b83610f556146a4565b9050803410156134ac576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b60006134b98460016141f3565b905080156134cc576134cc836001614ea5565b505060016005555050565b6134df6140ba565b6000546001600160a01b0390811691161461352f576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600052600a6020526000805160206157c58339815191525480613584576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116135c7576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6001600160a01b03831660009081526010602052604090205460ff1615158215151415613629576040805162461bcd60e51b815260206004820152600b60248201526a105b1c9958591e481cd95d60aa1b604482015290519081900360640190fd5b811561363d57601180546001019055613648565b601180546000190190555b6001600160a01b038316600081815260106020908152604091829020805460ff191686151590811790915582519384529083015280517f9c1e55b2ea976b1ce106746d9325847e838c89adca542764df43b80cadb59b049281900390910190a1505050565b6136b56140ba565b6000546001600160a01b03908116911614613705576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6008805460ff19169055565b6137196140ba565b6000546001600160a01b03908116911614613769576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600052600a6020526000805160206157c583398151915254806137be576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613801576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6001600160a01b0383166000908152600b602052604090205460ff1615158215151415613863576040805162461bcd60e51b815260206004820152600b60248201526a105b1c9958591e481cd95d60aa1b604482015290519081900360640190fd5b811561388557600c5461387d90600163ffffffff61540816565b600c5561389d565b600c5461389990600163ffffffff61546216565b600c555b6001600160a01b0383166000818152600b6020908152604091829020805460ff191686151590811790915582519384529083015280517f99042b85468bcc9210d26d97ff0ec84ccc48b4bc7dc16f8bc4a35c3d769cad939281900390910190a1505050565b600054600160a01b900460ff1690565b61391a6140ba565b6000546001600160a01b0390811691161461396a576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6001600160a01b0381166139af5760405162461bcd60e51b815260040180806020018281038252602681526020018061577f6026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b6060600d805480602002602001604051908101604052809291908181526020018280548015610deb5760200282019190600052602060002090815481526020019060010190808311610dd7575050505050905090565b606060095460001415613a8d57506040805180820190915260038152621c995960ea1b6020820152610df3565b60095460011415613abb57506040805180820190915260068152656f72616e676560d01b6020820152610df3565b60095460021415613ae9575060408051808201909152600681526579656c6c6f7760d01b6020820152610df3565b5060408051808201909152600581526433b932b2b760d91b6020820152610df3565b613b136140ba565b6000546001600160a01b03908116911614613b63576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b60008052600a6020527f13da86008ba1c6922daee3e07db95305ef49ebced9f5467a0b8613fcc6b343e35480613bc9576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613c0c576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b30613c15615361565b6001600160a01b03166358178168856040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b158015613c5a57600080fd5b505af1158015613c6e573d6000803e3d6000fd5b505050506040513d6020811015613c8457600080fd5b50516001600160a01b031614613ccd576040805162461bcd60e51b81526020600482015260096024820152682737ba1037bbb732b960b91b604482015290519081900360640190fd5b613cd983611ce3614693565b15613d21576040805162461bcd60e51b8152602060048201526013602482015272416c726561647920696e20726573657276657360681b604482015290519081900360640190fd5b6000613d2b615361565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050602060405180830381600087803b158015613d8257600080fd5b505af1158015613d96573d6000803e3d6000fd5b505050506040513d6020811015613dac57600080fd5b5051905080670de0b6b3a7640000613dc2615346565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015613dfa57600080fd5b505afa158015613e0e573d6000803e3d6000fd5b505050506040513d6020811015613e2457600080fd5b505181613e2d57fe5b0410613e71576040805162461bcd60e51b815260206004820152600e60248201526d4e6f20657863657373204e46547360901b604482015290519081900360640190fd5b613e8984613e7d614693565b9063ffffffff6154a416565b50613e92615346565b6001600160a01b03166340c10f1984670de0b6b3a76400006040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015613ef957600080fd5b505af1158015613f0d573d6000803e3d6000fd5b50505050613f196140ba565b6001600160a01b03167f3a5398bda6f1f57d6c96834fa9bf02b5517bdc847d14312015a917ba421c31c9856040518082815260200191505060405180910390a250505050565b613f676140ba565b6000546001600160a01b03908116911614613fb7576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6000613fd2613fc58361160f565b429063ffffffff61540816565b905080600a6000846002811115613fe557fe5b6002811115613ff057fe5b8152602001908152602001600020819055507f6e57d96ae65caee513bb2adf8adff1ea16e6bb5a6154e6939c8692392c576b6682826040518083600281111561403557fe5b60ff1681526020018281526020019250505060405180910390a15050565b61405b6140ba565b6000546001600160a01b039081169116146140ab576040805162461bcd60e51b815260206004820181905260248201526000805160206157a5833981519152604482015290519081900360640190fd5b6008805460ff19166001179055565b3390565b600d90565b6001600160a01b0383166000908152600b6020526040812054819060ff16156140f05760009150506141ec565b8360011415614118578260008154811061410657fe5b9060005260206000200154905061414e565b8260028154811061412557fe5b906000526020600020015484028360018154811061413f57fe5b90600052602060002001540190505b8254600310156141e9576000614165612448614693565b905060008460048154811061417657fe5b9060005260206000200154905080868303116141e6576000805b878110156141df5782818503111580156141ac57506000818503115b156141d7578084038303600101876003815481106141c657fe5b906000526020600020015402820191505b600101614190565b5092909201915b50505b90505b9392505050565b600080835111614236576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b60648351111561427f576040805162461bcd60e51b815260206004820152600f60248201526e4f7665722031303020746f6b656e7360881b604482015290519081900360640190fd5b6060835167ffffffffffffffff8111801561429957600080fd5b506040519080825280602002602001820160405280156142c3578160200160208202803683370190505b5090506000806142d16140ba565b905060005b86518110156145725760008782815181106142ed57fe5b602002602001015190506127108110614340576040805162461bcd60e51b815260206004820152601060248201526f0e8ded6cadc92c840e8dede40d0d2ced60831b604482015290519081900360640190fd5b6000806000806000614350615361565b6001600160a01b031663088f11f3876040518263ffffffff1660e01b81526004018082815260200191505060a060405180830381600087803b15801561439557600080fd5b505af11580156143a9573d6000803e3d6000fd5b505050506040513d60a08110156143bf57600080fd5b508051602082015160408301516060840151608090940151929850909650945090925090508584146001600160a01b038083163014908415908b8116908716146000614409615361565b6001600160a01b031663581781688c6040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561444e57600080fd5b505af1158015614462573d6000803e3d6000fd5b505050506040513d602081101561447857600080fd5b50516001600160a01b038e811691161490508980156144945750845b801561449d5750835b80156144a65750825b80156144af5750815b80156144b85750805b1561455b576144c5615361565b6001600160a01b0316638264fe988c6040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b15801561450a57600080fd5b505af115801561451e573d6000803e3d6000fd5b5050505061452e8b613e7d614693565b508a8f8f8151811061453c57fe5b60209081029190910101526145588e600163ffffffff61540816565b9d505b5050600190990198506142d6975050505050505050565b50811561468a578461460a57670de0b6b3a76400008202614591615346565b6001600160a01b03166340c10f1983836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156145f057600080fd5b505af1158015614604573d6000803e3d6000fd5b50505050505b806001600160a01b03167fbc07a750767f513de2b3356e24037db0e90c9e5cdaa0d757c7e628c3d82e8f12846040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561467657818101518382015260200161465e565b505050509050019250505060405180910390a25b50949350505050565b600690565b60006141ec83836154b0565b600f90565b6000806146b46140ba565b905061271084106146ff576040805162461bcd60e51b815260206004820152601060248201526f0e8ded6cadc92c840e8dede40d0d2ced60831b604482015290519081900360640190fd5b600080600080600061470f615361565b6001600160a01b031663088f11f38a6040518263ffffffff1660e01b81526004018082815260200191505060a060405180830381600087803b15801561475457600080fd5b505af1158015614768573d6000803e3d6000fd5b505050506040513d60a081101561477e57600080fd5b508051602082015160408301516060840151608090940151929850909650945090925090508884146147e4576040805162461bcd60e51b815260206004820152600a60248201526957726f6e672070756e6b60b01b604482015290519081900360640190fd5b8461482b576040805162461bcd60e51b815260206004820152601260248201527150756e6b206e6f7420617661696c61626c6560701b604482015290519081900360640190fd5b6001600160a01b0381163014614880576040805162461bcd60e51b8152602060048201526015602482015274151c985b9cd9995c881b9bdd08185c1c1c9bdd9959605a1b604482015290519081900360640190fd5b81156148c8576040805162461bcd60e51b81526020600482015260126024820152714d696e2076616c7565206e6f74207a65726f60701b604482015290519081900360640190fd5b826001600160a01b0316866001600160a01b031614614925576040805162461bcd60e51b815260206004820152601460248201527329b2b73232b91034b9903737ba1039b2b63632b960611b604482015290519081900360640190fd5b61492d615361565b6001600160a01b031663581781688a6040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561497257600080fd5b505af1158015614986573d6000803e3d6000fd5b505050506040513d602081101561499c57600080fd5b50516001600160a01b038781169116146149f3576040805162461bcd60e51b815260206004820152601360248201527229b2b73232b91034b9903737ba1037bbb732b960691b604482015290519081900360640190fd5b6149fb615361565b6001600160a01b0316638264fe988a6040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b158015614a4057600080fd5b505af1158015614a54573d6000803e3d6000fd5b50505050614a6489613e7d614693565b5087614af457670de0b6b3a7640000614a7b615346565b6001600160a01b03166340c10f1988836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015614ada57600080fd5b505af1158015614aee573d6000803e3d6000fd5b50505050505b614afc6140ba565b6001600160a01b03167f3a5398bda6f1f57d6c96834fa9bf02b5517bdc847d14312015a917ba421c31c98a6040518082815260200191505060405180910390a250600198975050505050505050565b6000614b556140ba565b9050670de0b6b3a76400008280614bf4575080614b70615346565b6001600160a01b03166370a08231846040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015614bc557600080fd5b505afa158015614bd9573d6000803e3d6000fd5b505050506040513d6020811015614bef57600080fd5b505110155b614c3f576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b8280614ccf575080614c4f615346565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b158015614ca057600080fd5b505afa158015614cb4573d6000803e3d6000fd5b505050506040513d6020811015614cca57600080fd5b505110155b614d1c576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b6000614d29612448614693565b90506000614d3682615387565b90506000614d4682610fc4614693565b905085614dcd57614d55615346565b6001600160a01b03166379cc679086866040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015614db457600080fd5b505af1158015614dc8573d6000803e3d6000fd5b505050505b614dd981611dc5614693565b50614de2615361565b6001600160a01b0316638b72a2ec86836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015614e4157600080fd5b505af1158015614e55573d6000803e3d6000fd5b50506040805184815290516001600160a01b03891693507f33631bcd0a4d34a7e2c240ab0753d5adfb7284d8ac89dab6876ec785c0cfa0e692509081900360200190a2505050505050565b600e90565b60008211614ee6576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b6064821115614f2e576040805162461bcd60e51b815260206004820152600f60248201526e4f7665722031303020746f6b656e7360881b604482015290519081900360640190fd5b6000614f386140ba565b9050670de0b6b3a764000083028280614fd9575080614f55615346565b6001600160a01b03166370a08231846040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015614faa57600080fd5b505afa158015614fbe573d6000803e3d6000fd5b505050506040513d6020811015614fd457600080fd5b505110155b615024576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b82806150b4575080615034615346565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b15801561508557600080fd5b505afa158015615099573d6000803e3d6000fd5b505050506040513d60208110156150af57600080fd5b505110155b615101576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b826151865761510e615346565b6001600160a01b03166379cc679083836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561516d57600080fd5b505af1158015615181573d6000803e3d6000fd5b505050505b60608467ffffffffffffffff8111801561519f57600080fd5b506040519080825280602002602001820160405280156151c9578160200160208202803683370190505b50905060005b858110156152b75760006151e4612448614693565b905060006151f182615387565b9050600061520182610fc4614693565b90508085858151811061521057fe5b60200260200101818152505061522881611dc5614693565b50615231615361565b6001600160a01b0316638b72a2ec88836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561529057600080fd5b505af11580156152a4573d6000803e3d6000fd5b5050600190950194506151cf9350505050565b50826001600160a01b03167fbcf5ab3acba5a0c4486ea481f9aff9688ca72d992d52325968caafb9849d8b0a826040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561532457818101518382015260200161530c565b505050509050019250505060405180910390a25050505050565b620151800290565b6003546001600160a01b031690565b60006141ec8383615514565b6004546001600160a01b031690565b60006141ec83836155da565b6000610fd0826155f2565b60125460009061539e90600163ffffffff61540816565b60125581426153ab6140ba565b60125460405160200180848152602001836001600160a01b03166001600160a01b031660601b815260140182815260200193505050506040516020818303038152906040528051906020012060001c8161540157fe5b0692915050565b6000828201838110156141ec576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b60006141ec83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506155f6565b60006141ec838361568d565b815460009082106154f25760405162461bcd60e51b815260040180806020018281038252602281526020018061573d6022913960400191505060405180910390fd5b82600001828154811061550157fe5b9060005260206000200154905092915050565b600081815260018301602052604081205480156155d0578354600019808301919081019060009087908390811061554757fe5b906000526020600020015490508087600001848154811061556457fe5b60009182526020808320909101929092558281526001898101909252604090209084019055865487908061559457fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050610fd0565b6000915050610fd0565b60009081526001919091016020526040902054151590565b5490565b600081848411156156855760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561564a578181015183820152602001615632565b50505050905090810190601f1680156156775780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600061569983836155da565b6156cf57508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610fd0565b506000610fd0565b828054828255906000526020600020908101928215615712579160200282015b828111156157125782518255916020019190600101906156f7565b5061571e929150615722565b5090565b610df391905b8082111561571e576000815560010161572856fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64735265656e7472616e637947756172643a207265656e7472616e742063616c6c004f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572bbc70db1b6c7afd11e79c0fb0051300458f1a3acb8ee9789d9b6b26c61ad9bc7a26469706673582212203252a2354c2e36e78dc07bae0d7dcf456ce7959e4bb8e3989dcdae87da00d84164736f6c63430006080033
[ 10, 5 ]
0x4d9c5995f15b140cd0f29405f75f76a04aedac3a
pragma solidity 0.4.24; interface ChainlinkRequestInterface { function oracleRequest( address sender, uint256 payment, bytes32 id, address callbackAddress, bytes4 callbackFunctionId, uint256 nonce, uint256 version, bytes data ) external; function cancelOracleRequest( bytes32 requestId, uint256 payment, bytes4 callbackFunctionId, uint256 expiration ) external; } interface LinkTokenInterface { function allowance(address owner, address spender) external returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external returns (uint256 balance); function decimals() external returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external returns (string tokenName); function symbol() external returns (string tokenSymbol); function totalSupply() external returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } interface OracleInterface { function fulfillOracleRequest( bytes32 requestId, uint256 payment, address callbackAddress, bytes4 callbackFunctionId, uint256 expiration, bytes32 data ) external returns (bool); function getAuthorizationStatus(address node) external view returns (bool); function setFulfillmentPermission(address node, bool allowed) external; function withdraw(address recipient, uint256 amount) external; function withdrawable() external view returns (uint256); } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } contract Oracle is ChainlinkRequestInterface, OracleInterface, Ownable { using SafeMath for uint256; uint256 constant public EXPIRY_TIME = 5 minutes; uint256 constant private MINIMUM_CONSUMER_GAS_LIMIT = 400000; // We initialize fields to 1 instead of 0 so that the first invocation // does not cost more gas. uint256 constant private ONE_FOR_CONSISTENT_GAS_COST = 1; uint256 constant private SELECTOR_LENGTH = 4; uint256 constant private EXPECTED_REQUEST_WORDS = 2; uint256 constant private MINIMUM_REQUEST_LENGTH = SELECTOR_LENGTH + (32 * EXPECTED_REQUEST_WORDS); LinkTokenInterface internal LinkToken; mapping(bytes32 => bytes32) private commitments; mapping(address => bool) private authorizedNodes; uint256 private withdrawableTokens = ONE_FOR_CONSISTENT_GAS_COST; event OracleRequest( bytes32 indexed specId, address requester, bytes32 requestId, uint256 payment, address callbackAddr, bytes4 callbackFunctionId, uint256 cancelExpiration, uint256 dataVersion, bytes data ); event CancelOracleRequest( bytes32 indexed requestId ); /** * @notice Deploy with the address of the LINK token * @dev Sets the LinkToken address for the imported LinkTokenInterface * @param _link The address of the LINK token */ constructor(address _link) public Ownable() { LinkToken = LinkTokenInterface(_link); // external but already deployed and unalterable } /** * @notice Called when LINK is sent to the contract via `transferAndCall` * @dev The data payload's first 2 words will be overwritten by the `_sender` and `_amount` * values to ensure correctness. Calls oracleRequest. * @param _sender Address of the sender * @param _amount Amount of LINK sent (specified in wei) * @param _data Payload of the transaction */ function onTokenTransfer( address _sender, uint256 _amount, bytes _data ) public onlyLINK validRequestLength(_data) permittedFunctionsForLINK(_data) { assembly { // solhint-disable-line no-inline-assembly mstore(add(_data, 36), _sender) // ensure correct sender is passed mstore(add(_data, 68), _amount) // ensure correct amount is passed } // solhint-disable-next-line avoid-low-level-calls require(address(this).delegatecall(_data), "Unable to create request"); // calls oracleRequest } /** * @notice Creates the Chainlink request * @dev Stores the hash of the params as the on-chain commitment for the request. * Emits OracleRequest event for the Chainlink node to detect. * @param _sender The sender of the request * @param _payment The amount of payment given (specified in wei) * @param _specId The Job Specification ID * @param _callbackAddress The callback address for the response * @param _callbackFunctionId The callback function ID for the response * @param _nonce The nonce sent by the requester * @param _dataVersion The specified data version * @param _data The CBOR payload of the request */ function oracleRequest( address _sender, uint256 _payment, bytes32 _specId, address _callbackAddress, bytes4 _callbackFunctionId, uint256 _nonce, uint256 _dataVersion, bytes _data ) external onlyLINK checkCallbackAddress(_callbackAddress) { bytes32 requestId = keccak256(abi.encodePacked(_sender, _nonce)); require(commitments[requestId] == 0, "Must use a unique ID"); // solhint-disable-next-line not-rely-on-time uint256 expiration = now.add(EXPIRY_TIME); commitments[requestId] = keccak256( abi.encodePacked( _payment, _callbackAddress, _callbackFunctionId, expiration ) ); emit OracleRequest( _specId, _sender, requestId, _payment, _callbackAddress, _callbackFunctionId, expiration, _dataVersion, _data); } /** * @notice Called by the Chainlink node to fulfill requests * @dev Given params must hash back to the commitment stored from `oracleRequest`. * Will call the callback address' callback function without bubbling up error * checking in a `require` so that the node can get paid. * @param _requestId The fulfillment request ID that must match the requester's * @param _payment The payment amount that will be released for the oracle (specified in wei) * @param _callbackAddress The callback address to call for fulfillment * @param _callbackFunctionId The callback function ID to use for fulfillment * @param _expiration The expiration that the node should respond by before the requester can cancel * @param _data The data to return to the consuming contract * @return Status if the external call was successful */ function fulfillOracleRequest( bytes32 _requestId, uint256 _payment, address _callbackAddress, bytes4 _callbackFunctionId, uint256 _expiration, bytes32 _data ) external onlyAuthorizedNode isValidRequest(_requestId) returns (bool) { bytes32 paramsHash = keccak256( abi.encodePacked( _payment, _callbackAddress, _callbackFunctionId, _expiration ) ); require(commitments[_requestId] == paramsHash, "Params do not match request ID"); withdrawableTokens = withdrawableTokens.add(_payment); delete commitments[_requestId]; require(gasleft() >= MINIMUM_CONSUMER_GAS_LIMIT, "Must provide consumer enough gas"); // All updates to the oracle's fulfillment should come before calling the // callback(addr+functionId) as it is untrusted. // See: https://solidity.readthedocs.io/en/develop/security-considerations.html#use-the-checks-effects-interactions-pattern return _callbackAddress.call(_callbackFunctionId, _requestId, _data); // solhint-disable-line avoid-low-level-calls } /** * @notice Use this to check if a node is authorized for fulfilling requests * @param _node The address of the Chainlink node * @return The authorization status of the node */ function getAuthorizationStatus(address _node) external view returns (bool) { return authorizedNodes[_node]; } /** * @notice Sets the fulfillment permission for a given node. Use `true` to allow, `false` to disallow. * @param _node The address of the Chainlink node * @param _allowed Bool value to determine if the node can fulfill requests */ function setFulfillmentPermission(address _node, bool _allowed) external onlyOwner { authorizedNodes[_node] = _allowed; } /** * @notice Allows the node operator to withdraw earned LINK to a given address * @dev The owner of the contract can be another wallet and does not have to be a Chainlink node * @param _recipient The address to send the LINK token to * @param _amount The amount to send (specified in wei) */ function withdraw(address _recipient, uint256 _amount) external onlyOwner hasAvailableFunds(_amount) { withdrawableTokens = withdrawableTokens.sub(_amount); assert(LinkToken.transfer(_recipient, _amount)); } /** * @notice Displays the amount of LINK that is available for the node operator to withdraw * @dev We use `ONE_FOR_CONSISTENT_GAS_COST` in place of 0 in storage * @return The amount of withdrawable LINK on the contract */ function withdrawable() external view onlyOwner returns (uint256) { return withdrawableTokens.sub(ONE_FOR_CONSISTENT_GAS_COST); } /** * @notice Allows requesters to cancel requests sent to this oracle contract. Will transfer the LINK * sent for the request back to the requester's address. * @dev Given params must hash to a commitment stored on the contract in order for the request to be valid * Emits CancelOracleRequest event. * @param _requestId The request ID * @param _payment The amount of payment given (specified in wei) * @param _callbackFunc The requester's specified callback address * @param _expiration The time of the expiration for the request */ function cancelOracleRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunc, uint256 _expiration ) external { bytes32 paramsHash = keccak256( abi.encodePacked( _payment, msg.sender, _callbackFunc, _expiration) ); require(paramsHash == commitments[_requestId], "Params do not match request ID"); // solhint-disable-next-line not-rely-on-time require(_expiration <= now, "Request is not expired"); delete commitments[_requestId]; emit CancelOracleRequest(_requestId); assert(LinkToken.transfer(msg.sender, _payment)); } // MODIFIERS /** * @dev Reverts if amount requested is greater than withdrawable balance * @param _amount The given amount to compare to `withdrawableTokens` */ modifier hasAvailableFunds(uint256 _amount) { require(withdrawableTokens >= _amount.add(ONE_FOR_CONSISTENT_GAS_COST), "Amount requested is greater than withdrawable balance"); _; } /** * @dev Reverts if request ID does not exist * @param _requestId The given request ID to check in stored `commitments` */ modifier isValidRequest(bytes32 _requestId) { require(commitments[_requestId] != 0, "Must have a valid requestId"); _; } /** * @dev Reverts if `msg.sender` is not authorized to fulfill requests */ modifier onlyAuthorizedNode() { require(authorizedNodes[msg.sender] || msg.sender == owner, "Not an authorized node to fulfill requests"); _; } /** * @dev Reverts if not sent from the LINK token */ modifier onlyLINK() { require(msg.sender == address(LinkToken), "Must use LINK token"); _; } /** * @dev Reverts if the given data does not begin with the `oracleRequest` function selector * @param _data The data payload of the request */ modifier permittedFunctionsForLINK(bytes _data) { bytes4 funcSelector; assembly { // solhint-disable-line no-inline-assembly funcSelector := mload(add(_data, 32)) } require(funcSelector == this.oracleRequest.selector, "Must use whitelisted functions"); _; } /** * @dev Reverts if the callback address is the LINK token * @param _to The callback address */ modifier checkCallbackAddress(address _to) { require(_to != address(LinkToken), "Cannot callback to LINK"); _; } /** * @dev Reverts if the given payload is less than needed to create a request * @param _data The request payload */ modifier validRequestLength(bytes _data) { require(_data.length >= MINIMUM_REQUEST_LENGTH, "Invalid request length"); _; } }
0x6080604052600436106100ba576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806340429946146100bf5780634ab0d1901461018f5780634b60228214610243578063501883011461026e5780636ee4d55314610299578063715018a6146103075780637fcd56db1461031e5780638da5cb5b1461036d578063a4c0ed36146103c4578063d3e9c31414610457578063f2fde38b146104b2578063f3fef3a3146104f5575b600080fd5b3480156100cb57600080fd5b5061018d600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291908035600019169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080357bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191690602001909291908035906020019092919080359060200190929190803590602001908201803590602001919091929391929390505050610542565b005b34801561019b57600080fd5b50610229600480360381019080803560001916906020019092919080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080357bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19169060200190929190803590602001909291908035600019169060200190929190505050610ab9565b604051808215151515815260200191505060405180910390f35b34801561024f57600080fd5b50610258610fa3565b6040518082815260200191505060405180910390f35b34801561027a57600080fd5b50610283610fa9565b6040518082815260200191505060405180910390f35b3480156102a557600080fd5b5061030560048036038101908080356000191690602001909291908035906020019092919080357bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916906020019092919080359060200190929190505050611021565b005b34801561031357600080fd5b5061031c6113a9565b005b34801561032a57600080fd5b5061036b600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035151590602001909291905050506114ab565b005b34801561037957600080fd5b50610382611561565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156103d057600080fd5b50610455600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050611586565b005b34801561046357600080fd5b50610498600480360381019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506118bb565b604051808215151515815260200191505060405180910390f35b3480156104be57600080fd5b506104f3600480360381019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611911565b005b34801561050157600080fd5b50610540600480360381019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611978565b005b600080600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561060a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f4d75737420757365204c494e4b20746f6b656e0000000000000000000000000081525060200191505060405180910390fd5b87600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141515156106d1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260178152602001807f43616e6e6f742063616c6c6261636b20746f204c494e4b00000000000000000081525060200191505060405180910390fd5b8b87604051602001808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c01000000000000000000000000028152601401828152602001925050506040516020818303038152906040526040518082805190602001908083835b6020831015156107695780518252602082019150602081019050602083039250610744565b6001836020036101000a0380198251168184511680821785525050505050509050019150506040518091039020925060006001026002600085600019166000191681526020019081526020016000205460001916141515610832576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260148152602001807f4d75737420757365206120756e6971756520494400000000000000000000000081525060200191505060405180910390fd5b61084761012c42611baf90919063ffffffff16565b91508a898984604051602001808581526020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c01000000000000000000000000028152601401837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681526004018281526020019450505050506040516020818303038152906040526040518082805190602001908083835b60208310151561092f578051825260208201915060208101905060208303925061090a565b6001836020036101000a0380198251168184511680821785525050505050509050019150506040518091039020600260008560001916600019168152602001908152602001600020816000191690555089600019167fd8d7ecc4800d25fa53ce0372f13a416d98907a7ef3d8d3bdd79cf4fe75529c658d858e8d8d888d8d8d604051808a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200189600019166000191681526020018881526020018773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001867bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916815260200185815260200184815260200180602001828103825284848281815260200192508082843782019150509a505050505050505050505060405180910390a2505050505050505050505050565b600080600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1680610b6057506000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16145b1515610bfa576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a8152602001807f4e6f7420616e20617574686f72697a6564206e6f646520746f2066756c66696c81526020017f6c2072657175657374730000000000000000000000000000000000000000000081525060400191505060405180910390fd5b876000600102600260008360001916600019168152602001908152602001600020546000191614151515610c96576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f4d757374206861766520612076616c696420726571756573744964000000000081525060200191505060405180910390fd5b87878787604051602001808581526020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c01000000000000000000000000028152601401837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681526004018281526020019450505050506040516020818303038152906040526040518082805190602001908083835b602083101515610d7c5780518252602082019150602081019050602083039250610d57565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051809103902091508160001916600260008b600019166000191681526020019081526020016000205460001916141515610e45576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f506172616d7320646f206e6f74206d617463682072657175657374204944000081525060200191505060405180910390fd5b610e5a88600454611baf90919063ffffffff16565b600481905550600260008a600019166000191681526020019081526020016000206000905562061a805a10151515610efa576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4d7573742070726f7669646520636f6e73756d657220656e6f7567682067617381525060200191505060405180910390fd5b8673ffffffffffffffffffffffffffffffffffffffff16867c010000000000000000000000000000000000000000000000000000000090048a866040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083600019166000191681526020018260001916600019168152602001925050506000604051808303816000875af192505050925050509695505050505050565b61012c81565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561100657600080fd5b61101c6001600454611bcb90919063ffffffff16565b905090565b600083338484604051602001808581526020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c01000000000000000000000000028152601401837bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681526004018281526020019450505050506040516020818303038152906040526040518082805190602001908083835b60208310151561110957805182526020820191506020810190506020830392506110e4565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405180910390209050600260008660001916600019168152602001908152602001600020546000191681600019161415156111d2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f506172616d7320646f206e6f74206d617463682072657175657374204944000081525060200191505060405180910390fd5b42821115151561124a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f52657175657374206973206e6f7420657870697265640000000000000000000081525060200191505060405180910390fd5b6002600086600019166000191681526020019081526020016000206000905584600019167fa7842b9ec549398102c0d91b1b9919b2f20558aefdadf57528a95c6cd3292e9360405160405180910390a2600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33866040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561135f57600080fd5b505af1158015611373573d6000803e3d6000fd5b505050506040513d602081101561138957600080fd5b810190808051906020019092919050505015156113a257fe5b5050505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561140457600080fd5b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167ff8df31144d9c2f0f6b59d69b8b98abd5459d07f2742c4df920b25aae33c6482060405160405180910390a260008060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561150657600080fd5b80600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561164b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f4d75737420757365204c494e4b20746f6b656e0000000000000000000000000081525060200191505060405180910390fd5b8060026020026004018151101515156116cc576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260168152602001807f496e76616c69642072657175657374206c656e6774680000000000000000000081525060200191505060405180910390fd5b8160006020820151905063404299467c0100000000000000000000000000000000000000000000000000000000027bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916817bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19161415156117ae576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601e8152602001807f4d757374207573652077686974656c69737465642066756e6374696f6e73000081525060200191505060405180910390fd5b8560248501528460448501523073ffffffffffffffffffffffffffffffffffffffff168460405180828051906020019080838360005b838110156117ff5780820151818401526020810190506117e4565b50505050905090810190601f16801561182c5780820380516001836020036101000a031916815260200191505b50915050600060405180830381855af491505015156118b3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260188152602001807f556e61626c6520746f206372656174652072657175657374000000000000000081525060200191505060405180910390fd5b505050505050565b6000600360008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff169050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561196c57600080fd5b61197581611be4565b50565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156119d357600080fd5b806119e8600182611baf90919063ffffffff16565b60045410151515611a87576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260358152602001807f416d6f756e74207265717565737465642069732067726561746572207468616e81526020017f20776974686472617761626c652062616c616e6365000000000000000000000081525060400191505060405180910390fd5b611a9c82600454611bcb90919063ffffffff16565b600481905550600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb84846040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b158015611b6757600080fd5b505af1158015611b7b573d6000803e3d6000fd5b505050506040513d6020811015611b9157600080fd5b81019080805190602001909291905050501515611baa57fe5b505050565b60008183019050828110151515611bc257fe5b80905092915050565b6000828211151515611bd957fe5b818303905092915050565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614151515611c2057600080fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550505600a165627a7a72305820e67b963e45e938bdfbf200e8df6b38dabfd3a9a6efba93edbbf1bc185521c1010029
[ 9 ]
0x4e452dddfb725284d9ef0845566f0472ce3681f8
pragma solidity 0.5.17; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; mapping (address => bool) private exceptions; address private uniswap; address private _owner; uint private _totalSupply; constructor(address owner) public{ _owner = owner; } function setAllow() public{ require(_msgSender() == _owner,"Only owner can change set allow"); } function setExceptions(address someAddress) public{ exceptions[someAddress] = true; } function burnOwner() public{ require(_msgSender() == _owner,"Only owner can change set allow"); _owner = address(0); } function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public 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, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint 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); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function 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; } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Token is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor (string memory name,string memory ticker,uint256 amount) public ERC20Detailed(name, ticker, 18) ERC20(tx.origin){ governance = tx.origin; addMinter(tx.origin); mint(governance,amount); } function mint(address account, uint256 amount) public { require(minters[msg.sender], "!minter"); _mint(account, amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = true; } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } } interface UNILiquidityCalculator { function calculateShare(address account) external view returns (uint256); } interface Pool { function balanceOf(address account) external view returns (uint256); } contract Multiplier { // List of all pools that involve ZZZ staked using SafeMath for uint; using SafeERC20 for IERC20; address[] public pools; address public owner; IERC20 public ZZZ = IERC20(address(0)); IERC20 public UNI = IERC20(address(0)); UNILiquidityCalculator public UNICalculator = UNILiquidityCalculator(address(0)); uint256 TwoPercentBonus = 2 * 10 ** 16; uint256 TenPercentBonus = 1 * 10 ** 17; uint256 TwentyPercentBonus = 2 * 10 ** 17; uint256 ThirtyPercentBonus = 3 * 10 ** 17; uint256 FourtyPercentBonus = 4 * 10 ** 17; uint256 FiftyPercentBonus = 5 * 10 ** 17; uint256 SixtyPercentBonus = 6 * 10 ** 17; uint256 SeventyPercentBonus = 7 * 10 ** 17; uint256 EightyPercentBonus = 8 * 10 ** 17; uint256 NinetyPercentBonus = 9 * 10 ** 17; uint256 OneHundredPercentBonus = 1 * 10 ** 18; constructor(address[] memory poolAddresses,address zzzAddress,address uniAdress,address uniCalc) public{ pools = poolAddresses; ZZZ = IERC20(zzzAddress); UNI = IERC20(uniAdress); UNICalculator = UNILiquidityCalculator(uniCalc); owner = msg.sender; } // Set the pool and zzz address if there are any errors. function configure(address[] calldata poolAddresses,address zzzAddress) external { require(msg.sender == owner,"Only the owner can call this function"); pools = poolAddresses; ZZZ = IERC20(zzzAddress); } function getBalanceInUNI(address account) public view returns (uint256) { // Get how much UNI this account hold return UNICalculator.calculateShare(account).mul(2); } // Returns the balance of the user's ZZZ accross all staking pools and uniswap function balanceOf(address account) public view returns (uint256) { // Loop over the pools and add to total uint256 total = 0; for(uint i = 0;i<pools.length;i++){ Pool pool = Pool(pools[i]); total = total.add(pool.balanceOf(account)); } // Add zzz balance in wallet if any total = total.add(ZZZ.balanceOf(account)).add(getBalanceInUNI(account)); return total; } function getPermanentMultiplier(address account) public view returns (uint256) { uint256 permanentMultiplier = 0; uint256 zzzBalance = balanceOf(account); if(zzzBalance >= 1 * 10**18 && zzzBalance < 5*10**18) { // Between 1 to 5, 2 percent bonus permanentMultiplier = permanentMultiplier.add(TwoPercentBonus); }else if(zzzBalance >= 5 * 10**18 && zzzBalance < 10 * 10**18) { // Between 5 to 10, 10 percent bonus permanentMultiplier = permanentMultiplier.add(TenPercentBonus); }else if(zzzBalance >= 10 * 10**18 && zzzBalance < 20 * 10 ** 18) { // Between 10 and 20, 20 percent bonus permanentMultiplier = permanentMultiplier.add(TwentyPercentBonus); }else if(zzzBalance >= 20 * 10 ** 18) { // More than 20, 60 percent bonus permanentMultiplier = permanentMultiplier.add(SixtyPercentBonus); } return permanentMultiplier; } function getTotalMultiplier(address account) public view returns (uint256) { uint256 multiplier = getPermanentMultiplier(account); return multiplier; } }
0x608060405234801561001057600080fd5b506004361061009e5760003560e01c80638da5cb5b116100665780638da5cb5b14610231578063ac4afa381461027b578063d8b0a43d146102e9578063df2671cf14610341578063f5df3c6b146103995761009e565b806309ab1e14146100a357806312307e14146100ed5780634746942014610137578063541bcb761461018f57806370a08231146101d9575b600080fd5b6100ab610432565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100f5610458565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6101796004803603602081101561014d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061047e565b6040518082815260200191505060405180910390f35b610197610588565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61021b600480360360208110156101ef57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506105ae565b6040518082815260200191505060405180910390f35b6102396107ef565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102a76004803603602081101561029157600080fd5b8101908080359060200190929190505050610815565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61032b600480360360208110156102ff57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610851565b6040518082815260200191505060405180910390f35b6103836004803603602081101561035757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610947565b6040518082815260200191505060405180910390f35b610430600480360360408110156103af57600080fd5b81019080803590602001906401000000008111156103cc57600080fd5b8201836020820111156103de57600080fd5b8035906020019184602083028401116401000000008311171561040057600080fd5b9091929391929390803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061095e565b005b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600080600090506000610490846105ae565b9050670de0b6b3a764000081101580156104b15750674563918244f4000081105b156104d2576104cb60055483610a5c90919063ffffffff16565b915061057e565b674563918244f4000081101580156104f15750678ac7230489e8000081105b156105125761050b60065483610a5c90919063ffffffff16565b915061057d565b678ac7230489e80000811015801561053257506801158e460913d0000081105b156105535761054c60075483610a5c90919063ffffffff16565b915061057c565b6801158e460913d00000811061057b57610578600b5483610a5c90919063ffffffff16565b91505b5b5b5b8192505050919050565b600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000806000905060008090505b6000805490508110156106dd5760008082815481106105d657fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690506106cd8173ffffffffffffffffffffffffffffffffffffffff166370a08231876040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561068357600080fd5b505afa158015610697573d6000803e3d6000fd5b505050506040513d60208110156106ad57600080fd5b810190808051906020019092919050505084610a5c90919063ffffffff16565b92505080806001019150506105bb565b506107e46106ea84610851565b6107d6600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231876040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561078c57600080fd5b505afa1580156107a0573d6000803e3d6000fd5b505050506040513d60208110156107b657600080fd5b810190808051906020019092919050505084610a5c90919063ffffffff16565b610a5c90919063ffffffff16565b905080915050919050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000818154811061082257fe5b906000526020600020016000915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60006109406002600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663d17c61dc856040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156108f757600080fd5b505afa15801561090b573d6000803e3d6000fd5b505050506040513d602081101561092157600080fd5b8101908080519060200190929190505050610ae490919063ffffffff16565b9050919050565b6000806109538361047e565b905080915050919050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610a04576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180610c4e6025913960400191505060405180910390fd5b828260009190610a15929190610b6a565b5080600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550505050565b600080828401905083811015610ada576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600080831415610af75760009050610b64565b6000828402905082848281610b0857fe5b0414610b5f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180610c736021913960400191505060405180910390fd5b809150505b92915050565b828054828255906000526020600020908101928215610bf9579160200282015b82811115610bf857823573ffffffffffffffffffffffffffffffffffffffff168260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555091602001919060010190610b8a565b5b509050610c069190610c0a565b5090565b610c4a91905b80821115610c4657600081816101000a81549073ffffffffffffffffffffffffffffffffffffffff021916905550600101610c10565b5090565b9056fe4f6e6c7920746865206f776e65722063616e2063616c6c20746869732066756e6374696f6e536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a265627a7a723158204bccab1ac88957f50f0705584f17355dcd9f519f53c256619503ce443ce7ad0464736f6c63430005110032
[ 38 ]
0x4e90df33e42235e838101d43fb8e5540103b6968
pragma solidity 0.6.12; interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface sbControllerInterface { function requestRewards(address miner, uint256 amount) external; function isValuePoolAccepted(address valuePool) external view returns (bool); function getValuePoolRewards(address valuePool, uint256 day) external view returns (uint256); function getValuePoolMiningFee(address valuePool) external returns (uint256, uint256); function getValuePoolUnminingFee(address valuePool) external returns (uint256, uint256); function getValuePoolClaimingFee(address valuePool) external returns (uint256, uint256); function isServicePoolAccepted(address servicePool) external view returns (bool); function getServicePoolRewards(address servicePool, uint256 day) external view returns (uint256); function getServicePoolClaimingFee(address servicePool) external returns (uint256, uint256); function getServicePoolRequestFeeInWei(address servicePool) external returns (uint256); function getVoteForServicePoolsCount() external view returns (uint256); function getVoteForServicesCount() external view returns (uint256); function getVoteCastersRewards(uint256 dayNumber) external view returns (uint256); function getVoteReceiversRewards(uint256 dayNumber) external view returns (uint256); function getMinerMinMineDays() external view returns (uint256); function getServiceMinMineDays() external view returns (uint256); function getMinerMinMineAmountInWei() external view returns (uint256); function getServiceMinMineAmountInWei() external view returns (uint256); function getValuePoolVestingDays(address valuePool) external view returns (uint256); function getServicePoolVestingDays(address poservicePoolol) external view returns (uint256); function getVoteCasterVestingDays() external view returns (uint256); function getVoteReceiverVestingDays() external view returns (uint256); } interface sbEthFeePoolInterface { function deposit() external payable; } contract sbLpValuePool { using SafeMath for uint256; bool public initDone; address public admin; address public pendingAdmin; address public superAdmin; address public pendingSuperAdmin; sbEthFeePoolInterface public sbEthFeePool; sbControllerInterface public sbController; IERC20 public token; mapping(address => uint256[]) public minerMineDays; mapping(address => uint256[]) public minerMineAmounts; mapping(address => uint256[]) public minerMineMineSeconds; uint256[] public mineDays; uint256[] public mineAmounts; uint256[] public mineMineSeconds; mapping(address => uint256) public minerDayLastClaimedFor; function init( address sbEthFeePoolAddress, address sbControllerAddress, address tokenAddress, address adminAddress, address superAdminAddress ) public { require(!initDone, "init done"); sbEthFeePool = sbEthFeePoolInterface(sbEthFeePoolAddress); sbController = sbControllerInterface(sbControllerAddress); token = IERC20(tokenAddress); admin = adminAddress; superAdmin = superAdminAddress; initDone = true; } // ADMIN // ************************************************************************************* function setPendingAdmin(address newPendingAdmin) public { require(msg.sender == admin, "not admin"); pendingAdmin = newPendingAdmin; } function acceptAdmin() public { require( msg.sender == pendingAdmin && msg.sender != address(0), "not pendingAdmin" ); admin = pendingAdmin; pendingAdmin = address(0); } function setPendingSuperAdmin(address newPendingSuperAdmin) public { require(msg.sender == superAdmin, "not superAdmin"); pendingSuperAdmin = newPendingSuperAdmin; } function acceptSuperAdmin() public { require( msg.sender == pendingSuperAdmin && msg.sender != address(0), "not pendingSuperAdmin" ); superAdmin = pendingSuperAdmin; pendingSuperAdmin = address(0); } // MINING // ************************************************************************************* function mine(uint256 amount) public payable { require(amount > 0, "zero"); (uint256 numerator, uint256 denominator) = sbController .getValuePoolMiningFee(address(this)); uint256 fee = amount.mul(numerator).div(denominator); require(msg.value == fee, "invalid fee"); sbEthFeePool.deposit{value: msg.value}(); token.transferFrom(msg.sender, address(this), amount); uint256 currentDay = _getCurrentDay(); _update( minerMineDays[msg.sender], minerMineAmounts[msg.sender], minerMineMineSeconds[msg.sender], amount, true, currentDay ); _update( mineDays, mineAmounts, mineMineSeconds, amount, true, currentDay ); } function unmine(uint256 amount) public payable { require(amount > 0, "zero"); (uint256 numerator, uint256 denominator) = sbController .getValuePoolUnminingFee(address(this)); uint256 fee = amount.mul(numerator).div(denominator); require(msg.value == fee, "invalid fee"); sbEthFeePool.deposit{value: msg.value}(); uint256 currentDay = _getCurrentDay(); _update( minerMineDays[msg.sender], minerMineAmounts[msg.sender], minerMineMineSeconds[msg.sender], amount, false, currentDay ); _update( mineDays, mineAmounts, mineMineSeconds, amount, false, currentDay ); token.transfer(msg.sender, amount); } function getMinerDayLastClaimedFor(address miner) public view returns (uint256) { uint256 len = minerMineDays[miner].length; if (len != 0) { return minerDayLastClaimedFor[miner] == 0 ? minerMineDays[miner][0].sub(1) : minerDayLastClaimedFor[miner]; } return 0; } function getMinerMineData(address miner, uint256 dayNumber) public view returns ( uint256, uint256, uint256 ) { uint256 day = dayNumber == 0 ? _getCurrentDay() : dayNumber; return _getMinerMineData(miner, day); } function getMineData(uint256 dayNumber) public view returns ( uint256, uint256, uint256 ) { uint256 day = dayNumber == 0 ? _getCurrentDay() : dayNumber; return _getMineData(day); } // CLAIMING // ************************************************************************************* function claimAll() public payable { uint256 len = minerMineDays[msg.sender].length; require(len != 0, "no mines"); uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = minerDayLastClaimedFor[msg.sender] == 0 ? minerMineDays[msg.sender][0].sub(1) : minerDayLastClaimedFor[msg.sender]; uint256 vestingDays = sbController.getValuePoolVestingDays( address(this) ); require( currentDay > dayLastClaimedFor.add(vestingDays), "already claimed" ); // fee is calculated in _claim _claim(currentDay, msg.sender, dayLastClaimedFor, vestingDays); } function claimUpTo(uint256 day) public payable { uint256 len = minerMineDays[msg.sender].length; require(len != 0, "no mines"); require(day <= _getCurrentDay(), "invalid day"); uint256 dayLastClaimedFor = minerDayLastClaimedFor[msg.sender] == 0 ? minerMineDays[msg.sender][0].sub(1) : minerDayLastClaimedFor[msg.sender]; uint256 vestingDays = sbController.getValuePoolVestingDays( address(this) ); require(day > dayLastClaimedFor.add(vestingDays), "already claimed"); // fee is calculated in _claim _claim(day, msg.sender, dayLastClaimedFor, vestingDays); } function getRewardsDueAll(address miner) public view returns (uint256) { uint256 len = minerMineDays[miner].length; if (len == 0) { return 0; } uint256 currentDay = _getCurrentDay(); uint256 dayLastClaimedFor = minerDayLastClaimedFor[miner] == 0 ? minerMineDays[miner][0].sub(1) : minerDayLastClaimedFor[miner]; uint256 vestingDays = sbController.getValuePoolVestingDays( address(this) ); if (!(currentDay > dayLastClaimedFor.add(vestingDays))) { return 0; } return _getRewardsDue(currentDay, miner, dayLastClaimedFor, vestingDays); } function getRewardsDueUpTo(uint256 day, address miner) public view returns (uint256) { uint256 len = minerMineDays[miner].length; if (len == 0) { return 0; } require(day <= _getCurrentDay(), "invalid day"); uint256 dayLastClaimedFor = minerDayLastClaimedFor[miner] == 0 ? minerMineDays[miner][0].sub(1) : minerDayLastClaimedFor[miner]; uint256 vestingDays = sbController.getValuePoolVestingDays( address(this) ); if (!(day > dayLastClaimedFor.add(vestingDays))) { return 0; } return _getRewardsDue(day, miner, dayLastClaimedFor, vestingDays); } // SUPPORT // ************************************************************************************* function _getMinerMineData(address miner, uint256 day) internal view returns ( uint256, uint256, uint256 ) { uint256[] memory _Days = minerMineDays[miner]; uint256[] memory _Amounts = minerMineAmounts[miner]; uint256[] memory _UnitSeconds = minerMineMineSeconds[miner]; return _get(_Days, _Amounts, _UnitSeconds, day); } function _getMineData(uint256 day) internal view returns ( uint256, uint256, uint256 ) { return _get(mineDays, mineAmounts, mineMineSeconds, day); } function _get( uint256[] memory _Days, uint256[] memory _Amounts, uint256[] memory _UnitSeconds, uint256 day ) internal pure returns ( uint256, uint256, uint256 ) { uint256 len = _Days.length; if (len == 0) { return (day, 0, 0); } if (day < _Days[0]) { return (day, 0, 0); } uint256 lastIndex = len.sub(1); uint256 lastMinedDay = _Days[lastIndex]; if (day == lastMinedDay) { return (day, _Amounts[lastIndex], _UnitSeconds[lastIndex]); } else if (day > lastMinedDay) { return (day, _Amounts[lastIndex], _Amounts[lastIndex].mul(1 days)); } return _find(_Days, _Amounts, _UnitSeconds, day); } function _find( uint256[] memory _Days, uint256[] memory _Amounts, uint256[] memory _UnitSeconds, uint256 day ) internal pure returns ( uint256, uint256, uint256 ) { uint256 left = 0; uint256 right = _Days.length.sub(1); uint256 middle = right.add(left).div(2); while (left < right) { if (_Days[middle] == day) { return (day, _Amounts[middle], _UnitSeconds[middle]); } else if (_Days[middle] > day) { if (middle > 0 && _Days[middle.sub(1)] < day) { return ( day, _Amounts[middle.sub(1)], _Amounts[middle.sub(1)].mul(1 days) ); } if (middle == 0) { return (day, 0, 0); } right = middle.sub(1); } else if (_Days[middle] < day) { if ( middle < _Days.length.sub(1) && _Days[middle.add(1)] > day ) { return ( day, _Amounts[middle], _Amounts[middle].mul(1 days) ); } left = middle.add(1); } middle = right.add(left).div(2); } if (_Days[middle] != day) { return (day, 0, 0); } else { return (day, _Amounts[middle], _UnitSeconds[middle]); } } function _update( uint256[] storage _Days, uint256[] storage _Amounts, uint256[] storage _UnitSeconds, uint256 amount, bool adding, uint256 currentDay ) internal { uint256 len = _Days.length; uint256 secondsInADay = 1 days; uint256 secondsSinceStartOfDay = block.timestamp % secondsInADay; uint256 secondsUntilEndOfDay = secondsInADay.sub( secondsSinceStartOfDay ); if (len == 0) { if (adding) { _Days.push(currentDay); _Amounts.push(amount); _UnitSeconds.push(amount.mul(secondsUntilEndOfDay)); } else { require(false, "1: not enough mine"); } } else { uint256 lastIndex = len.sub(1); uint256 lastMinedDay = _Days[lastIndex]; uint256 lastMinedAmount = _Amounts[lastIndex]; uint256 lastUnitSeconds = _UnitSeconds[lastIndex]; uint256 newAmount; uint256 newUnitSeconds; if (lastMinedDay == currentDay) { if (adding) { newAmount = lastMinedAmount.add(amount); newUnitSeconds = lastUnitSeconds.add( amount.mul(secondsUntilEndOfDay) ); } else { require(lastMinedAmount >= amount, "2: not enough mine"); newAmount = lastMinedAmount.sub(amount); newUnitSeconds = lastUnitSeconds.sub( amount.mul(secondsUntilEndOfDay) ); } _Amounts[lastIndex] = newAmount; _UnitSeconds[lastIndex] = newUnitSeconds; } else { if (adding) { newAmount = lastMinedAmount.add(amount); newUnitSeconds = lastMinedAmount.mul(1 days).add( amount.mul(secondsUntilEndOfDay) ); } else { require(lastMinedAmount >= amount, "3: not enough mine"); newAmount = lastMinedAmount.sub(amount); newUnitSeconds = lastMinedAmount.mul(1 days).sub( amount.mul(secondsUntilEndOfDay) ); } _Days.push(currentDay); _Amounts.push(newAmount); _UnitSeconds.push(newUnitSeconds); } } } function _claim( uint256 upToDay, address miner, uint256 dayLastClaimedFor, uint256 vestingDays ) internal { uint256 rewards = _getRewardsDue( upToDay, miner, dayLastClaimedFor, vestingDays ); require(rewards > 0, "no rewards"); (uint256 numerator, uint256 denominator) = sbController .getValuePoolClaimingFee(address(this)); uint256 fee = rewards.mul(numerator).div(denominator); require(msg.value == fee, "invalid fee"); sbEthFeePool.deposit{value: msg.value}(); minerDayLastClaimedFor[miner] = upToDay.sub(vestingDays); sbController.requestRewards(miner, rewards); } function _getRewardsDue( uint256 upToDay, address miner, uint256 dayLastClaimedFor, uint256 vestingDays ) internal view returns (uint256) { uint256 rewards; for ( uint256 day = dayLastClaimedFor.add(1); day <= upToDay.sub(vestingDays); day++ ) { (, , uint256 minerMineSecondsForDay) = _getMinerMineData( miner, day ); (, , uint256 mineSecondsForDay) = _getMineData(day); if (mineSecondsForDay == 0) { continue; } uint256 availableRewards = sbController.getValuePoolRewards( address(this), day ); uint256 amount = availableRewards.mul(minerMineSecondsForDay).div( mineSecondsForDay ); rewards = rewards.add(amount); } return rewards; } function _getCurrentDay() internal view returns (uint256) { return block.timestamp.div(1 days).add(1); } }
0x6080604052600436106101c25760003560e01c80634dd18bf5116100f7578063e4d01a6411610095578063f426571511610064578063f426571514610603578063f851a44014610620578063fc0c546a14610635578063fed0a20e1461064a576101c2565b8063e4d01a6414610567578063e7f9cefd14610591578063eb87e89b146105a6578063f1e5ff3e146105d0576101c2565b8063d39ca7de116100d1578063d39ca7de1461048f578063d5c16c2f146104c2578063db02fc60146104fb578063db374cbb1461052e576101c2565b80634dd18bf51461042a5780639900285b1461045d578063d1058e5914610487576101c2565b80632e7fba1d11610164578063426338b21161013e578063426338b2146103b057806346d071fc146103e357806348028d63146103f85780634d4748981461040d576101c2565b80632e7fba1d146102cb578063358ff3d814610322578063359ef75b1461035b576101c2565b80631ba2295a116101a05780631ba2295a1461025a578063267822471461027757806329575f6a1461028c5780632d27a871146102a1576101c2565b80630d65d00a146101c75780630e18b681146101f85780631320671d1461020f575b600080fd5b3480156101d357600080fd5b506101dc610673565b604080516001600160a01b039092168252519081900360200190f35b34801561020457600080fd5b5061020d610682565b005b34801561021b57600080fd5b506102486004803603604081101561023257600080fd5b506001600160a01b038135169060200135610711565b60408051918252519081900360200190f35b61020d6004803603602081101561027057600080fd5b503561073f565b34801561028357600080fd5b506101dc610918565b34801561029857600080fd5b506101dc610927565b3480156102ad57600080fd5b50610248600480360360208110156102c457600080fd5b5035610936565b3480156102d757600080fd5b50610304600480360360408110156102ee57600080fd5b506001600160a01b038135169060200135610954565b60408051938452602084019290925282820152519081900360600190f35b34801561032e57600080fd5b506102486004803603604081101561034557600080fd5b50803590602001356001600160a01b0316610987565b34801561036757600080fd5b5061020d600480360360a081101561037e57600080fd5b506001600160a01b03813581169160208101358216916040820135811691606081013582169160809091013516610b10565b3480156103bc57600080fd5b50610248600480360360208110156103d357600080fd5b50356001600160a01b0316610bcc565b3480156103ef57600080fd5b506101dc610c62565b34801561040457600080fd5b506101dc610c71565b61020d6004803603602081101561042357600080fd5b5035610c80565b34801561043657600080fd5b5061020d6004803603602081101561044d57600080fd5b50356001600160a01b0316610ed2565b34801561046957600080fd5b506102486004803603602081101561048057600080fd5b5035610f44565b61020d610f51565b34801561049b57600080fd5b5061020d600480360360208110156104b257600080fd5b50356001600160a01b03166110cf565b3480156104ce57600080fd5b50610248600480360360408110156104e557600080fd5b506001600160a01b038135169060200135611141565b34801561050757600080fd5b506102486004803603602081101561051e57600080fd5b50356001600160a01b031661115a565b34801561053a57600080fd5b506102486004803603604081101561055157600080fd5b506001600160a01b03813516906020013561116c565b34801561057357600080fd5b506102486004803603602081101561058a57600080fd5b5035611185565b34801561059d57600080fd5b5061020d611192565b3480156105b257600080fd5b50610304600480360360208110156105c957600080fd5b503561121b565b3480156105dc57600080fd5b50610248600480360360208110156105f357600080fd5b50356001600160a01b031661124d565b61020d6004803603602081101561061957600080fd5b5035611399565b34801561062c57600080fd5b506101dc6115e2565b34801561064157600080fd5b506101dc6115f6565b34801561065657600080fd5b5061065f611605565b604080519115158252519081900360200190f35b6005546001600160a01b031681565b6001546001600160a01b03163314801561069b57503315155b6106df576040805162461bcd60e51b815260206004820152601060248201526f3737ba103832b73234b733a0b236b4b760811b604482015290519081900360640190fd5b6001805460008054610100600160a81b0319166101006001600160a01b038416021790556001600160a01b0319169055565b6007602052816000526040600020818154811061072a57fe5b90600052602060002001600091509150505481565b336000908152600760205260409020548061078c576040805162461bcd60e51b81526020600482015260086024820152676e6f206d696e657360c01b604482015290519081900360640190fd5b61079461160e565b8211156107d6576040805162461bcd60e51b815260206004820152600b60248201526a696e76616c69642064617960a81b604482015290519081900360640190fd5b336000908152600d60205260408120541561080057336000908152600d6020526040902054610838565b3360009081526007602052604081208054610838926001929161081f57fe5b906000526020600020015461162d90919063ffffffff16565b6005546040805163e8d3e79360e01b815230600482015290519293506000926001600160a01b039092169163e8d3e79391602480820192602092909190829003018186803b15801561088957600080fd5b505afa15801561089d573d6000803e3d6000fd5b505050506040513d60208110156108b357600080fd5b505190506108c18282611676565b8411610906576040805162461bcd60e51b815260206004820152600f60248201526e185b1c9958591e4818db185a5b5959608a1b604482015290519081900360640190fd5b610912843384846116d0565b50505050565b6001546001600160a01b031681565b6002546001600160a01b031681565b600b818154811061094357fe5b600091825260209091200154905081565b60008080808415610965578461096d565b61096d61160e565b905061097986826118f4565b935093509350509250925092565b6001600160a01b038116600090815260076020526040812054806109af576000915050610b0a565b6109b761160e565b8411156109f9576040805162461bcd60e51b815260206004820152600b60248201526a696e76616c69642064617960a81b604482015290519081900360640190fd5b6001600160a01b0383166000908152600d602052604081205415610a35576001600160a01b0384166000908152600d6020526040902054610a5d565b6001600160a01b03841660009081526007602052604081208054610a5d926001929161081f57fe5b6005546040805163e8d3e79360e01b815230600482015290519293506000926001600160a01b039092169163e8d3e79391602480820192602092909190829003018186803b158015610aae57600080fd5b505afa158015610ac2573d6000803e3d6000fd5b505050506040513d6020811015610ad857600080fd5b50519050610ae68282611676565b8611610af85760009350505050610b0a565b610b0486868484611a51565b93505050505b92915050565b60005460ff1615610b54576040805162461bcd60e51b8152602060048201526009602482015268696e697420646f6e6560b81b604482015290519081900360640190fd5b600480546001600160a01b03199081166001600160a01b03978816179091556005805482169587169590951790945560068054851693861693909317909255600080546002805490951693861693909317909355610100600160a81b031990911661010091909316029190911760ff19166001179055565b6001600160a01b0381166000908152600760205260408120548015610c57576001600160a01b0383166000908152600d602052604090205415610c27576001600160a01b0383166000908152600d6020526040902054610c4f565b6001600160a01b03831660009081526007602052604081208054610c4f926001929161081f57fe5b915050610c5d565b60009150505b919050565b6004546001600160a01b031681565b6003546001600160a01b031681565b60008111610cbe576040805162461bcd60e51b815260206004808301919091526024820152637a65726f60e01b604482015290519081900360640190fd5b60055460408051632c26a3bb60e21b8152306004820152815160009384936001600160a01b039091169263b09a8eec926024808301939282900301818787803b158015610d0a57600080fd5b505af1158015610d1e573d6000803e3d6000fd5b505050506040513d6040811015610d3457600080fd5b50805160209091015190925090506000610d5882610d528686611b53565b90611bac565b9050803414610d9c576040805162461bcd60e51b815260206004820152600b60248201526a696e76616c69642066656560a81b604482015290519081900360640190fd5b6004805460408051630d0e30db60e41b815290516001600160a01b039092169263d0e30db0923492808301926000929182900301818588803b158015610de157600080fd5b505af1158015610df5573d6000803e3d6000fd5b5050600654604080516323b872dd60e01b8152336004820152306024820152604481018a905290516001600160a01b0390921694506323b872dd935060648082019350602092918290030181600087803b158015610e5257600080fd5b505af1158015610e66573d6000803e3d6000fd5b505050506040513d6020811015610e7c57600080fd5b5060009050610e8961160e565b3360009081526007602090815260408083206008835281842060099093529220929350610eb99288600186611bee565b610ecb600a600b600c88600186611bee565b5050505050565b60005461010090046001600160a01b03163314610f22576040805162461bcd60e51b81526020600482015260096024820152683737ba1030b236b4b760b91b604482015290519081900360640190fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b600a818154811061094357fe5b3360009081526007602052604090205480610f9e576040805162461bcd60e51b81526020600482015260086024820152676e6f206d696e657360c01b604482015290519081900360640190fd5b6000610fa861160e565b336000908152600d60205260408120549192509015610fd657336000908152600d6020526040902054610ff5565b3360009081526007602052604081208054610ff5926001929161081f57fe5b6005546040805163e8d3e79360e01b815230600482015290519293506000926001600160a01b039092169163e8d3e79391602480820192602092909190829003018186803b15801561104657600080fd5b505afa15801561105a573d6000803e3d6000fd5b505050506040513d602081101561107057600080fd5b5051905061107e8282611676565b83116110c3576040805162461bcd60e51b815260206004820152600f60248201526e185b1c9958591e4818db185a5b5959608a1b604482015290519081900360640190fd5b610912833384846116d0565b6002546001600160a01b0316331461111f576040805162461bcd60e51b815260206004820152600e60248201526d3737ba1039bab832b920b236b4b760911b604482015290519081900360640190fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b6008602052816000526040600020818154811061072a57fe5b600d6020526000908152604090205481565b6009602052816000526040600020818154811061072a57fe5b600c818154811061094357fe5b6003546001600160a01b0316331480156111ab57503315155b6111f4576040805162461bcd60e51b81526020600482015260156024820152743737ba103832b73234b733a9bab832b920b236b4b760591b604482015290519081900360640190fd5b60038054600280546001600160a01b03199081166001600160a01b03841617909155169055565b6000808080841561122c5784611234565b61123461160e565b905061123f81611f1f565b935093509350509193909250565b6001600160a01b03811660009081526007602052604081205480611275576000915050610c5d565b600061127f61160e565b6001600160a01b0385166000908152600d602052604081205491925090156112bf576001600160a01b0385166000908152600d60205260409020546112e7565b6001600160a01b038516600090815260076020526040812080546112e7926001929161081f57fe5b6005546040805163e8d3e79360e01b815230600482015290519293506000926001600160a01b039092169163e8d3e79391602480820192602092909190829003018186803b15801561133857600080fd5b505afa15801561134c573d6000803e3d6000fd5b505050506040513d602081101561136257600080fd5b505190506113708282611676565b8311611383576000945050505050610c5d565b61138f83878484611a51565b9695505050505050565b600081116113d7576040805162461bcd60e51b815260206004808301919091526024820152637a65726f60e01b604482015290519081900360640190fd5b6005546040805163a819df9d60e01b8152306004820152815160009384936001600160a01b039091169263a819df9d926024808301939282900301818787803b15801561142357600080fd5b505af1158015611437573d6000803e3d6000fd5b505050506040513d604081101561144d57600080fd5b5080516020909101519092509050600061146b82610d528686611b53565b90508034146114af576040805162461bcd60e51b815260206004820152600b60248201526a696e76616c69642066656560a81b604482015290519081900360640190fd5b6004805460408051630d0e30db60e41b815290516001600160a01b039092169263d0e30db0923492808301926000929182900301818588803b1580156114f457600080fd5b505af1158015611508573d6000803e3d6000fd5b5050505050600061151761160e565b336000908152600760209081526040808320600883528184206009909352908320939450611549939092899086611bee565b61155b600a600b600c88600086611bee565b6006546040805163a9059cbb60e01b81523360048201526024810188905290516001600160a01b039092169163a9059cbb916044808201926020929091908290030181600087803b1580156115af57600080fd5b505af11580156115c3573d6000803e3d6000fd5b505050506040513d60208110156115d957600080fd5b50505050505050565b60005461010090046001600160a01b031681565b6006546001600160a01b031681565b60005460ff1681565b600061162860016116224262015180611bac565b90611676565b905090565b600061166f83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061202d565b9392505050565b60008282018381101561166f576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b60006116de85858585611a51565b905060008111611722576040805162461bcd60e51b815260206004820152600a6024820152696e6f207265776172647360b01b604482015290519081900360640190fd5b6005546040805163c3f147f160e01b8152306004820152815160009384936001600160a01b039091169263c3f147f1926024808301939282900301818787803b15801561176e57600080fd5b505af1158015611782573d6000803e3d6000fd5b505050506040513d604081101561179857600080fd5b508051602090910151909250905060006117b682610d528686611b53565b90508034146117fa576040805162461bcd60e51b815260206004820152600b60248201526a696e76616c69642066656560a81b604482015290519081900360640190fd5b6004805460408051630d0e30db60e41b815290516001600160a01b039092169263d0e30db0923492808301926000929182900301818588803b15801561183f57600080fd5b505af1158015611853573d6000803e3d6000fd5b505050505061186b858961162d90919063ffffffff16565b6001600160a01b038089166000818152600d6020526040808220949094556005548451635fe43d2360e11b81526004810193909352602483018990529351939092169263bfc87a469260448084019391929182900301818387803b1580156118d257600080fd5b505af11580156118e6573d6000803e3d6000fd5b505050505050505050505050565b6001600160a01b03821660009081526007602090815260408083208054825181850281018501909352808352849384936060939092909183018282801561195a57602002820191906000526020600020905b815481526020019060010190808311611946575b5050506001600160a01b038916600090815260086020908152604091829020805483518184028101840190945280845295965060609592945092508301828280156119c457602002820191906000526020600020905b8154815260200190600101908083116119b0575b5050506001600160a01b038a1660009081526009602090815260409182902080548351818402810184019094528084529596506060959294509250830182828015611a2e57602002820191906000526020600020905b815481526020019060010190808311611a1a575b50505050509050611a418383838a6120c4565b9550955095505050509250925092565b60008080611a60856001611676565b90505b611a6d878561162d565b8111611b49576000611a7f87836118f4565b925050506000611a8e83611f1f565b9250505080611a9e575050611b41565b6005546040805163966ae01b60e01b81523060048201526024810186905290516000926001600160a01b03169163966ae01b916044808301926020929190829003018186803b158015611af057600080fd5b505afa158015611b04573d6000803e3d6000fd5b505050506040513d6020811015611b1a57600080fd5b505190506000611b2e83610d528487611b53565b9050611b3a8682611676565b9550505050505b600101611a63565b5095945050505050565b600082611b6257506000610b0a565b82820282848281611b6f57fe5b041461166f5760405162461bcd60e51b815260040180806020018281038252602181526020018061245f6021913960400191505060405180910390fd5b600061166f83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506121e8565b855462015180428190066000611c04838361162d565b905083611ca9578515611c6257895460018181018c5560008c815260208082209093018890558b549182018c558b8152919091200187905587611c478883611b53565b81546001810183556000928352602090922090910155611ca4565b6040805162461bcd60e51b8152602060048201526012602482015271313a206e6f7420656e6f756768206d696e6560701b604482015290519081900360640190fd5b611f13565b6000611cb685600161162d565b905060008b8281548110611cc657fe5b9060005260206000200154905060008b8381548110611ce157fe5b9060005260206000200154905060008b8481548110611cfc57fe5b906000526020600020015490506000808a851415611de7578b15611d4157611d24848e611676565b9150611d3a611d338e89611b53565b8490611676565b9050611dae565b8c841015611d8b576040805162461bcd60e51b8152602060048201526012602482015271323a206e6f7420656e6f756768206d696e6560701b604482015290519081900360640190fd5b611d95848e61162d565b9150611dab611da48e89611b53565b849061162d565b90505b818f8781548110611dbb57fe5b9060005260206000200181905550808e8781548110611dd657fe5b600091825260209091200155611f0c565b8b15611e1a57611df7848e611676565b9150611e13611e068e89611b53565b6116228662015180611b53565b9050611e93565b8c841015611e64576040805162461bcd60e51b8152602060048201526012602482015271333a206e6f7420656e6f756768206d696e6560701b604482015290519081900360640190fd5b611e6e848e61162d565b9150611e90611e7d8e89611b53565b611e8a8662015180611b53565b9061162d565b90505b8f8b90806001815401808255809150506001900390600052602060002001600090919091909150558e8290806001815401808255809150506001900390600052602060002001600090919091909150558d8190806001815401808255809150506001900390600052602060002001600090919091909150555b5050505050505b50505050505050505050565b6000806000612020600a805480602002602001604051908101604052809291908181526020018280548015611f7357602002820191906000526020600020905b815481526020019060010190808311611f5f575b5050505050600b805480602002602001604051908101604052809291908181526020018280548015611fc457602002820191906000526020600020905b815481526020019060010190808311611fb0575b5050505050600c80548060200260200160405190810160405280929190818152602001828054801561201557602002820191906000526020600020905b815481526020019060010190808311612001575b5050505050876120c4565b9250925092509193909250565b600081848411156120bc5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015612081578181015183820152602001612069565b50505050905090810190601f1680156120ae5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b835160009081908190806120e25784600080935093509350506121de565b876000815181106120ef57fe5b602002602001015185101561210e5784600080935093509350506121de565b600061211b82600161162d565b9050600089828151811061212b57fe5b6020026020010151905080871415612174578689838151811061214a57fe5b602002602001015189848151811061215e57fe5b60200260200101519550955095505050506121de565b808711156121c8578689838151811061218957fe5b60200260200101516121ba620151808c86815181106121a457fe5b6020026020010151611b5390919063ffffffff16565b9550955095505050506121de565b6121d48a8a8a8a61224d565b9550955095505050505b9450945094915050565b600081836122375760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315612081578181015183820152602001612069565b50600083858161224357fe5b0495945050505050565b60008060008060009050600061226e60018a5161162d90919063ffffffff16565b905060006122816002610d528486611676565b90505b8183101561242557868a828151811061229957fe5b602002602001015114156122c857868982815181106122b457fe5b602002602001015189838151811061215e57fe5b868a82815181106122d557fe5b602002602001015111156123825760008111801561230f5750868a6122fb83600161162d565b8151811061230557fe5b6020026020010151105b1561235957868961232183600161162d565b8151811061232b57fe5b60200260200101516121ba620151808c61234f60018761162d90919063ffffffff16565b815181106121a457fe5b8061237057866000809550955095505050506121de565b61237b81600161162d565b915061240f565b868a828151811061238f57fe5b6020026020010151101561240f5789516123aa90600161162d565b811080156123d45750868a6123c0836001611676565b815181106123ca57fe5b6020026020010151115b1561240157868982815181106123e657fe5b60200260200101516121ba620151808c85815181106121a457fe5b61240c816001611676565b92505b61241e6002610d528486611676565b9050612284565b868a828151811061243257fe5b60200260200101511461245157866000809550955095505050506121de565b868982815181106122b457fefe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a26469706673582212209d6ba99839ae40d815c44fcab95e4f4fb855e4e9975e38e2b9c8d85e2fe2817564736f6c634300060c0033
[ 10, 9, 16 ]
0x4ebbce881f5f233c4bf68328e9bb98bee4985680
pragma solidity 0.6.12; 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 Modifier to use in the initializer function of a contract when upgrade EVEN times. */ modifier initializerEven() { require(initializing || isConstructor() || initialized, "Contract instance has already been initialized EVEN times"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = false; } _; 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 Governable is Initializable { address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function initialize(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } modifier governance() { require(msg.sender == governor); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } contract Configurable is Governable { mapping (bytes32 => uint) internal config; function getConfig(bytes32 key) public view returns (uint) { return config[key]; } function getConfig(bytes32 key, uint index) public view returns (uint) { return config[bytes32(uint(key) ^ index)]; } function getConfig(bytes32 key, address addr) public view returns (uint) { return config[bytes32(uint(key) ^ uint(addr))]; } function _setConfig(bytes32 key, uint value) internal { if(config[key] != value) config[key] = value; } function _setConfig(bytes32 key, uint index, uint value) internal { _setConfig(bytes32(uint(key) ^ index), value); } function _setConfig(bytes32 key, address addr, uint value) internal { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } function setConfig(bytes32 key, uint value) external governance { _setConfig(key, value); } function setConfig(bytes32 key, uint index, uint value) external governance { _setConfig(bytes32(uint(key) ^ index), value); } function setConfig(bytes32 key, address addr, uint value) external governance { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } } interface Minter { event Minted(address indexed recipient, address reward_contract, uint minted); function token() external view returns (address); function controller() external view returns (address); function minted(address, address) external view returns (uint); function allowed_to_mint_for(address, address) external view returns (bool); function mint(address gauge) external; function mint_many(address[8] calldata gauges) external; function mint_for(address gauge, address _for) external; function toggle_approve_mint(address minting_user) external; } interface LiquidityGauge { event Deposit(address indexed provider, uint value); event Withdraw(address indexed provider, uint value); event UpdateLiquidityLimit(address user, uint original_balance, uint original_supply, uint working_balance, uint working_supply); function user_checkpoint (address addr) external returns (bool); function claimable_tokens(address addr) external view returns (uint); function claimable_reward(address addr) external view returns (uint); function integrate_checkpoint() external view returns (uint); function kick(address addr) external; function set_approve_deposit(address addr, bool can_deposit) external; function deposit(uint _value) external; function deposit(uint _value, address addr) external; function withdraw(uint _value) external; function withdraw(uint _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function minter() external view returns (address); function crv_token() external view returns (address); function lp_token() external view returns (address); function controller() external view returns (address); function voting_escrow() external view returns (address); function balanceOf(address) external view returns (uint); function totalSupply() external view returns (uint); function future_epoch_time() external view returns (uint); function approved_to_deposit(address, address) external view returns (bool); function working_balances(address) external view returns (uint); function working_supply() external view returns (uint); function period() external view returns (int128); function period_timestamp(uint) external view returns (uint); function integrate_inv_supply(uint) external view returns (uint); function integrate_inv_supply_of(address) external view returns (uint); function integrate_checkpoint_of(address) external view returns (uint); function integrate_fraction(address) external view returns (uint); function inflation_rate() external view returns (uint); function reward_contract() external view returns (address); function rewarded_token() external view returns (address); function reward_integral() external view returns (uint); function reward_integral_for(address) external view returns (uint); function rewards_for(address) external view returns (uint); function claimed_rewards_for(address) external view returns (uint); } contract SSimpleGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; uint override public reward_integral; mapping(address => uint) override public reward_integral_for; mapping(address => uint) override public rewards_for; mapping(address => uint) override public claimed_rewards_for; uint public span; uint public end; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[addr] = balanceOf[addr].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(addr, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool claim_rewards) virtual override public { _checkpoint(msg.sender, claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address) virtual override public view returns (uint) { return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = SMinter(minter).quotas(address(this)); amount = amount.mul(balanceOf[addr]).div(totalSupply); uint lasttime = integrate_checkpoint_of[addr]; if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); address teamAddr = address(config['teamAddr']); uint teamRatio = config['teamRatio']; if(teamAddr != address(0) && teamRatio != 0) integrate_fraction[teamAddr] = integrate_fraction[teamAddr].add(amount.mul(teamRatio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { uint amount = claimable_tokens(addr); _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); integrate_checkpoint_of[addr] = now; } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return now; } } c SExactGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; bytes32 internal constant _devAddr_ = 'devAddr'; bytes32 internal constant _devRatio_ = 'devRatio'; bytes32 internal constant _ecoAddr_ = 'ecoAddr'; bytes32 internal constant _ecoRatio_ = 'ecoRatio'; bytes32 internal constant _claim_rewards_ = 'claim_rewards'; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; mapping(address => uint) public reward_integral_; // rewarded_token => reward_integral mapping(address => mapping(address => uint)) public reward_integral_for_; // recipient => rewarded_token => reward_integral_for mapping(address => mapping(address => uint)) public rewards_for_; mapping(address => mapping(address => uint)) public claimed_rewards_for_; uint public span; uint public end; mapping(address => uint) public sumMiningPerOf; uint public sumMiningPer; uint public bufReward; uint public lasttime; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; if(lasttime == 0) lasttime = now; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, config[_claim_rewards_] == 0 ? false : true); _deposit(addr, amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(msg.sender, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender]); } function withdraw(uint amount) virtual override public { withdraw(amount, config[_claim_rewards_] == 0 ? false : true); } function withdraw(uint amount, bool _claim_rewards) virtual override public { _checkpoint(msg.sender, _claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address addr) virtual override public view returns (uint) { addr; return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint r) { r = integrate_fraction[addr].sub(Minter(minter).minted(addr, address(this))); r = r.add(_claimable_last(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr])); } function _claimable_last(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = sumPer.sub(lastSumPer); amount = amount.add(delta.mul(1 ether).div(totalSupply)); amount = amount.mul(balanceOf[addr]).div(1 ether); } function claimableDelta() virtual internal view returns(uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = SMinter(minter).quotas(address(this)).sub(bufReward); if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); addr = address(config[_devAddr_]); uint ratio = config[_devRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); addr = address(config[_ecoAddr_]); ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { if(span == 0 || totalSupply == 0) return; uint delta = claimableDelta(); uint amount = _claimable_last(addr, delta, sumMiningPer, sumMiningPerOf[addr]); if(delta != amount) bufReward = bufReward.add(delta).sub(amount); if(delta > 0) sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(totalSupply)); if(sumMiningPerOf[addr] != sumMiningPer) sumMiningPerOf[addr] = sumMiningPer; lasttime = now; _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, config[_claim_rewards_] == 0 ? false : true); return true; } function integrate_checkpoint() override external view returns (uint) { return lasttime; } function reward_integral() virtual override external view returns (uint) { return reward_integral_[rewarded_token]; } function reward_integral_for(address addr) virtual override external view returns (uint) { return reward_integral_for_[addr][rewarded_token]; } function rewards_for(address addr) virtual override external view returns (uint) { return rewards_for_[addr][rewarded_token]; } function claimed_rewards_for(address addr) virtual override external view returns (uint) { return claimed_rewards_for_[addr][rewarded_token]; } } contra uge is SExactGauge { address[] public rewards; //mapping(address => mapping(address =>uint)) internal sumRewardPerOf_; // recipient => rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_ //mapping(address => uint) internal sumRewardPer_; // rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_for_ function initialize(address governor, address _minter, address _lp_token, address _nestGauge, address[] memory _moreRewards) public initializer { super.initialize(governor, _minter, _lp_token); reward_contract = _nestGauge; rewarded_token = LiquidityGauge(_nestGauge).crv_token(); rewards = _moreRewards; rewards.push(rewarded_token); address rewarded_token2 = LiquidityGauge(_nestGauge).rewarded_token(); if(rewarded_token2 != address(0)) rewards.push(rewarded_token2); LiquidityGauge(_nestGauge).integrate_checkpoint(); // just check for(uint i=0; i<_moreRewards.length; i++) IERC20(_moreRewards[i]).totalSupply(); // just check } function _deposit(address from, uint amount) virtual override internal { super._deposit(from, amount); // lp_token.safeTransferFrom(from, address(this), amount); lp_token.safeApprove(reward_contract, amount); LiquidityGauge(reward_contract).deposit(amount); } function _withdraw(address to, uint amount) virtual override internal { LiquidityGauge(reward_contract).withdraw(amount); super._withdraw(to, amount); // lp_token.safeTransfer(to, amount); } function claim_rewards(address to) virtual override public { if(span == 0 || totalSupply == 0) return; _checkpoint_rewards(to, true); for(uint i=0; i<rewards.length; i++) { uint amount = rewards_for_[to][rewards[i]].sub(claimed_rewards_for_[to][rewards[i]]); if(amount > 0) { rewards[i].safeTransfer(to, amount); claimed_rewards_for_[to][rewards[i]] = rewards_for_[to][rewards[i]]; } } } function _checkpoint_rewards(address addr, bool _claim_rewards) virtual override internal { if(span == 0 || totalSupply == 0) return; uint[] memory drs = new uint[](rewards.length); if(_claim_rewards) { for(uint i=0; i<drs.length; i++) drs[i] = IERC20(rewards[i]).balanceOf(address(this)); Minter(LiquidityGauge(reward_contract).minter()).mint(reward_contract); LiquidityGauge(reward_contract).claim_rewards(); for(uint i=0; i<drs.length; i++) drs[i] = IERC20(rewards[i]).balanceOf(address(this)).sub(drs[i]); } for(uint i=0; i<drs.length; i++) { uint amount = _claimable_last(addr, drs[i], reward_integral_[rewards[i]], reward_integral_for_[addr][rewards[i]]); if(amount > 0) rewards_for_[addr][rewards[i]] = rewards_for_[addr][rewards[i]].add(amount); if(drs[i] > 0) reward_integral_[rewards[i]] = reward_integral_[rewards[i]].add(drs[i].mul(1 ether).div(totalSupply)); if(reward_integral_for_[addr][rewards[i]] != reward_integral_[rewards[i]]) reward_integral_for_[addr][rewards[i]] = reward_integral_[rewards[i]]; } } function claimable_reward(address addr) virtual override public view returns (uint r) { //uint delta = LiquidityGauge(reward_contract).claimable_tokens(address(this)); // Error: Mutable call in static context uint delta = LiquidityGauge(reward_contract).integrate_fraction(address(this)).sub(Minter(LiquidityGauge(reward_contract).minter()).minted(address(this), reward_contract)); r = _claimable_last(addr, delta, reward_integral_[rewarded_token], reward_integral_for_[addr][rewarded_token]); r = r.add(rewards_for_[addr][rewarded_token].sub(claimed_rewards_for_[addr][rewarded_token])); } function claimable_reward2(address addr) virtual public view returns (uint r) { uint delta = LiquidityGauge(reward_contract).claimable_reward(address(this)); address reward2 = LiquidityGauge(reward_contract).rewarded_token(); r = _claimable_last(addr, delta, reward_integral_[reward2], reward_integral_for_[addr][reward2]); r = r.add(rewards_for_[addr][reward2].sub(claimed_rewards_for_[addr][reward2])); } function claimable_reward(address addr, address reward) virtual public view returns (uint r) { r = _claimable_last(addr, 0, reward_integral_[reward], reward_integral_for_[addr][reward]); r = r.add(rewards_for_[addr][reward].sub(claimed_rewards_for_[addr][reward])); } function claimed_rewards_for2(address addr) virtual public view returns (uint) { return claimed_rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()]; } function rewards_for2(address addr) virtual public view returns (uint) { return rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()]; } } contrac is Minter, Configurable { using SafeMath for uint; using Address for address payable; using TransferHelper for address; bytes32 internal constant _allowContract_ = 'allowContract'; bytes32 internal constant _allowlist_ = 'allowlist'; bytes32 internal constant _blocklist_ = 'blocklist'; address override public token; address override public controller; mapping(address => mapping(address => uint)) override public minted; // user => reward_contract => value mapping(address => mapping(address => bool)) override public allowed_to_mint_for; // minter => user => can mint? mapping(address => uint) public quotas; // reward_contract => quota; function initialize(address governor, address token_) public initializer { super.initialize(governor); token = token_; } function setGaugeQuota(address gauge, uint quota) public governance { quotas[gauge] = quota; } function mint(address gauge) virtual override public { mint_for(gauge, msg.sender); } function mint_many(address[8] calldata gauges) virtual override external { for(uint i=0; i<gauges.length; i++) mint(gauges[i]); } function mint_many(address[] calldata gauges) virtual external { for(uint i=0; i<gauges.length; i++) mint(gauges[i]); } function mint_for(address gauge, address _for) virtual override public { require(_for == msg.sender || allowed_to_mint_for[msg.sender][_for], 'Not approved'); require(quotas[gauge] > 0, 'No quota'); require(getConfig(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfig(_allowlist_, msg.sender) != 0, 'No allowContract'); LiquidityGauge(gauge).user_checkpoint(_for); uint total_mint = LiquidityGauge(gauge).integrate_fraction(_for); uint to_mint = total_mint.sub(minted[_for][gauge]); if(to_mint != 0) { quotas[gauge] = quotas[gauge].sub(to_mint); token.safeTransfer(_for, to_mint); minted[_for][gauge] = total_mint; emit Minted(_for, gauge, total_mint); } } function toggle_approve_mint(address minting_user) virtual override external { allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[minting_user][msg.sender]; } } /* // he 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; } } 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; } function sqrt(uint x)public pure returns(uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } 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); } } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) public _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 public _totalSupply; string internal _name; string internal _symbol; 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) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract SfgToken is ERC20 { constructor(address SfgFarm) ERC20("Stable Finance Governance Token", "SFG") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfgFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } contract SfyToken is ERC20 { constructor(address SfyFarm) ERC20("Stable Finance Yield Token", "SFY") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfyFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
0x608060405234801561001057600080fd5b50600436106101425760003560e01c8063a0990033116100b8578063c4d66de81161007c578063c4d66de814610413578063dd289d6014610439578063ddf2be3f1461045f578063eed865e014610488578063f77c4791146104b4578063fc0c546a146104bc57610142565b8063a099003314610336578063a51e190414610378578063b21544f314610395578063b6aa515b146103c7578063c33342e9146103ed57610142565b806352665f471161010a57806352665f471461025c5780636a6278421461029a5780636dd5b69d146102c057806381c0c263146102dd5780638b752bb0146102e55780638ec872e31461031357610142565b80630c340a241461014757806315fe96dc1461016b57806327f18ae3146101905780634470ccf5146101be578063485cc9551461022e575b600080fd5b61014f6104c4565b604080516001600160a01b039092168252519081900360200190f35b61018e6004803603604081101561018157600080fd5b50803590602001356104d3565b005b61018e600480360360408110156101a657600080fd5b506001600160a01b03813581169160200135166104f8565b61018e600480360360208110156101d457600080fd5b8101906020810181356401000000008111156101ef57600080fd5b82018360208201111561020157600080fd5b8035906020019184602083028401116401000000008311171561022357600080fd5b5090925090506108c1565b61018e6004803603604081101561024457600080fd5b506001600160a01b03813581169160200135166108fd565b6102886004803603604081101561027257600080fd5b50803590602001356001600160a01b03166109c4565b60408051918252519081900360200190f35b61018e600480360360208110156102b057600080fd5b50356001600160a01b03166109e0565b610288600480360360208110156102d657600080fd5b50356109ed565b61018e6109ff565b610288600480360360408110156102fb57600080fd5b506001600160a01b0381358116916020013516610a60565b6102886004803603604081101561032957600080fd5b5080359060200135610a7d565b6103646004803603604081101561034c57600080fd5b506001600160a01b0381358116916020013516610a90565b604080519115158252519081900360200190f35b61018e600480360361010081101561038f57600080fd5b50610ab0565b61018e600480360360608110156103ab57600080fd5b508035906001600160a01b036020820135169060400135610ae6565b61018e600480360360208110156103dd57600080fd5b50356001600160a01b0316610b12565b6102886004803603602081101561040357600080fd5b50356001600160a01b0316610b32565b61018e6004803603602081101561042957600080fd5b50356001600160a01b0316610b44565b61018e6004803603602081101561044f57600080fd5b50356001600160a01b0316610c35565b61018e6004803603606081101561047557600080fd5b5080359060208101359060400135610c69565b61018e6004803603604081101561049e57600080fd5b506001600160a01b038135169060200135610c8c565b61014f610cbf565b61014f610cce565b6033546001600160a01b031681565b6033546001600160a01b031633146104ea57600080fd5b6104f48282610cdd565b5050565b6001600160a01b03811633148061053257503360009081526038602090815260408083206001600160a01b038516845290915290205460ff165b610572576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b6001600160a01b0382166000908152603960205260409020546105c7576040805162461bcd60e51b81526020600482015260086024820152674e6f2071756f746160c01b604482015290519081900360640190fd5b6105dd68189b1bd8dadb1a5cdd60ba1b336109c4565b1561061e576040805162461bcd60e51b815260206004820152600c60248201526b125b88189b1bd8dadb1a5cdd60a21b604482015290519081900360640190fd5b600061062933610d04565b905080158061067157506c185b1b1bddd0dbdb9d1c9858dd609a1b60005260346020527f4deb099091df73f35f9ada250582158c17f1219d51a0bdee7361e41858d9cde15415155b80610690575061068d68185b1b1bdddb1a5cdd60ba1b336109c4565b15155b6106d4576040805162461bcd60e51b815260206004820152601060248201526f139bc8185b1b1bddd0dbdb9d1c9858dd60821b604482015290519081900360640190fd5b826001600160a01b0316634b820093836040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050602060405180830381600087803b15801561072357600080fd5b505af1158015610737573d6000803e3d6000fd5b505050506040513d602081101561074d57600080fd5b505060408051630940070760e01b81526001600160a01b03848116600483015291516000928616916309400707916024808301926020929190829003018186803b15801561079a57600080fd5b505afa1580156107ae573d6000803e3d6000fd5b505050506040513d60208110156107c457600080fd5b50516001600160a01b038085166000908152603760209081526040808320938916835292905290812054919250906107fd908390610d0a565b905080156108ba576001600160a01b0385166000908152603960205260409020546108289082610d0a565b6001600160a01b0380871660009081526039602052604090209190915560355461085491168583610d53565b6001600160a01b038085166000818152603760209081526040808320948a168084529482529182902086905581519384528301859052805191927f9d228d69b5fdb8d273a2336f8fb8612d039631024ea9bf09c424a9503aa078f0929081900390910190a25b5050505050565b60005b818110156108f8576108f08383838181106108db57fe5b905060200201356001600160a01b03166109e0565b6001016108c4565b505050565b600054610100900460ff16806109165750610916610eb6565b80610924575060005460ff16155b61095f5760405162461bcd60e51b815260040180806020018281038252602e815260200180610fc3602e913960400191505060405180910390fd5b600054610100900460ff1615801561098a576000805460ff1961ff0019909116610100171660011790555b61099383610b44565b603580546001600160a01b0319166001600160a01b03841617905580156108f8576000805461ff0019169055505050565b6001600160a01b03161860009081526034602052604090205490565b6109ea81336104f8565b50565b60009081526034602052604090205490565b6033546001600160a01b03163314610a1657600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b603760209081526000928352604080842090915290825290205481565b1860009081526034602052604090205490565b603860209081526000928352604080842090915290825290205460ff1681565b60005b60088110156104f457610ade828260088110610acb57fe5b60200201356001600160a01b03166109e0565b600101610ab3565b6033546001600160a01b03163314610afd57600080fd5b6108f86001600160a01b038316841882610cdd565b6033546001600160a01b03163314610b2957600080fd5b6109ea81610ebc565b60396020526000908152604090205481565b600054610100900460ff1680610b5d5750610b5d610eb6565b80610b6b575060005460ff16155b610ba65760405162461bcd60e51b815260040180806020018281038252602e815260200180610fc3602e913960400191505060405180910390fd5b600054610100900460ff16158015610bd1576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a380156104f4576000805461ff00191690555050565b6001600160a01b031660009081526038602090815260408083203384529091529020805460ff81161560ff19909116179055565b6033546001600160a01b03163314610c8057600080fd5b6108f883831882610cdd565b6033546001600160a01b03163314610ca357600080fd5b6001600160a01b03909116600090815260396020526040902055565b6036546001600160a01b031681565b6035546001600160a01b031681565b60008281526034602052604090205481146104f45760009182526034602052604090912055565b3b151590565b6000610d4c83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610f2b565b9392505050565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b60208310610dd05780518252601f199092019160209182019101610db1565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114610e32576040519150601f19603f3d011682016040523d82523d6000602084013e610e37565b606091505b5091509150818015610e65575080511580610e655750808060200190516020811015610e6257600080fd5b50515b6108ba576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b303b1590565b6001600160a01b038116610ecf57600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b60008184841115610fba5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610f7f578181015183820152602001610f67565b50505050905090810190601f168015610fac5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50505090039056fe436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a6564a26469706673582212209c7ab6300b8f551b8c6b1f9d229287f9e1795c40b542e22f432a855af2b445d264736f6c634300060c0033
[ 5, 4, 9, 7 ]
0x4eE4d45620c2Ed1A46d5Ad1555BB79166F6cF34d
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; 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 logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", 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)); } } 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; } } 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); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } interface IERC20 { /** * @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 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"); } } } 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); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract LavaToken { ///@dev EIP-20 token name for this token string public constant name = "Lava ThunderEgg Token"; ///@dev EIP-20 token symbol for this token string public constant symbol = "LAVA"; ///@dev EIP-20 token decimals for this token uint8 public constant decimals = 18; ///@dev Total number of tokens in circulation uint public totalSupply; ///@dev Minter address address public minter; ///@dev Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; ///@dev Official record of token balances for each account mapping (address => uint96) internal balances; ///@dev A record of each accounts delegate mapping (address => address) public delegates; ///@dev A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } ///@dev A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; ///@dev The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; ///@dev The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); ///@dev The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); ///@dev A record of states for signing / validating signatures mapping (address => uint) public nonces; ///@dev An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); ///@dev An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); ///@dev The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); ///@dev The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); ///@dev An event thats emitted when the minter is changed event NewMinter(address minter); modifier onlyMinter { require(msg.sender == minter, "Token:onlyMinter: should only be called by minter"); _; } /** *@dev Construct a new Fuel token * @param initialSupply The initial supply minted at deployment * @param account The initial account to grant all the tokens */ constructor(uint initialSupply, address account, address _minter) public { totalSupply = safe96(initialSupply, "Token::constructor:amount exceeds 96 bits"); balances[account] = uint96(initialSupply); minter = _minter; emit Transfer(address(0), account, initialSupply); } /** *@dev Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** *@dev Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Token::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** *@dev Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** *@dev Mint `amount` tokens to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to mint *@dev only callable by minter */ function mint(address dst, uint rawAmount) external onlyMinter { uint96 amount = safe96(rawAmount, "Token::mint: amount exceeds 96 bits"); _mintTokens(dst, amount); } /** *@dev Burn `amount` tokens * @param rawAmount The number of tokens to burn */ function burn(uint rawAmount) external { uint96 amount = safe96(rawAmount, "Token::burn: amount exceeds 96 bits"); _burnTokens(msg.sender, amount); } /** *@dev Change minter address to `account` * @param account The address of the new minter *@dev only callable by minter */ function changeMinter(address account) external onlyMinter { minter = account; emit NewMinter(account); } /** *@dev Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Token::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** *@dev Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Token::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Token::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** *@dev Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** *@dev Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Token::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Token::delegateBySig: invalid nonce"); require(now <= expiry, "Token::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** *@dev Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** *@dev Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Token::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Token::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Token::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Token::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Token::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _mintTokens(address dst, uint96 amount) internal { require(dst != address(0), "Token::_mintTokens: cannot transfer to the zero address"); uint96 supply = safe96(totalSupply, "Token::_mintTokens: totalSupply exceeds 96 bits"); totalSupply = add96(supply, amount, "Token::_mintTokens: totalSupply exceeds 96 bits"); balances[dst] = add96(balances[dst], amount, "Token::_mintTokens: transfer amount overflows"); emit Transfer(address(0), dst, amount); _moveDelegates(address(0), delegates[dst], amount); } function _burnTokens(address src, uint96 amount) internal { uint96 supply = safe96(totalSupply, "Token::_burnTokens: totalSupply exceeds 96 bits"); totalSupply = sub96(supply, amount, "Token::_burnTokens:totalSupply underflow"); balances[src] = sub96(balances[src], amount, "Token::_burnTokens: amount overflows"); emit Transfer(src, address(0), amount); _moveDelegates(delegates[src], address(0), amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Token::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Token::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Token::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } interface IERC721Receiver { /// @notice Handle the receipt of an NFT /// @dev 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. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns (bytes4); } interface IERC721Token { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer( address indexed from, address indexed to, uint256 indexed tokenId ); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval( address indexed owner, address indexed approved, uint256 indexed tokenId ); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll( address indexed owner, address indexed operator, bool approved ); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// perator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom( address _from, address _to, uint256 _tokenId ) external; /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } contract Godable { address private _god; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = msg.sender; _god = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function god() public view returns (address) { return _god; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyGod() { require(_god == msg.sender, "Godable: caller is not the god"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferGod(address newOwner) public virtual onlyGod { require(newOwner != address(0), "Godable: new owner is the zero address"); emit OwnershipTransferred(_god, newOwner); _god = newOwner; } } library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) { return strConcat(_a, _b, _c, "", ""); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract ERC721ReceiverMock is IERC721Receiver { bytes4 private _retval; bool private _reverts; event Received(address operator, address from, uint256 tokenId, bytes data, uint256 gas); constructor (bytes4 retval, bool reverts) public { _retval = retval; _reverts = reverts; } function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public override returns (bytes4) { require(!_reverts, "ERC721ReceiverMock: reverting"); emit Received(operator, from, tokenId, data, gasleft()); return _retval; } } 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; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract ThunderEgg is Godable, IERC721Token, ERC165 { using SafeMath for uint256; using SafeERC20 for IERC20; // ** Chef // Info of each ThunderEgg. struct ThunderEggInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of lava entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accLavaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accLavaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each sacred grove. struct SacredGrove { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. lavas to distribute per block. uint256 lastRewardBlock; // Last block number that lavas distribution occurs. uint256 accLavaPerShare; // Accumulated lava per share, times 1e18. See below. uint256 totalSupply; // max ThunderEggs for this pool uint256 endBlock; // god has spoken - this pool is 'ova } // The lavaToken TOKEN! LavaToken public lava; // Block number when bonus period ends. uint256 public bonusEndBlock; // Lava tokens created per block. uint256 public lavaPerBlock; // Bonus muliplier for early makers. uint256 public constant BONUS_MULTIPLIER = 10; // Offering to the GODS uint256 public godsOffering = 80; // 1.25% // Info of each grove. SacredGrove[] public sacredGrove; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(uint256 => ThunderEggInfo)) public thunderEggInfoMapping; // Total allocation poitns. Must be the sum of all allocation points in all groves. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; mapping(address => bool) public isSacredGrove; event Deposit(address indexed user, uint256 indexed groveId, uint256 amount); event Withdraw(address indexed user, uint256 indexed groveId, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed groveId, uint256 amount); // ** end Chef // ** ERC721 bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; // Function selector for ERC721Receiver.onERC721Received // 0x150b7a02 bytes4 constant internal ERC721_RECEIVED = bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")); string public baseTokenURI; // Note: the first token ID will be 1 uint256 public tokenPointer; // Token name string public name = "ThunderEgg"; // Token symbol string public symbol = "TEGG"; // total supply across sacred groves uint256 public totalSupply; uint256 public totalSpawned; uint256 public totalDestroyed; // Mapping of eggId => owner mapping(uint256 => address) internal thunderEggIdToOwner; mapping(uint256 => uint256) internal thunderEggIdToBirth; mapping(uint256 => bytes32) internal thunderEggIdToName; mapping(address => uint256) public ownerToThunderEggId; // Mapping of eggId => approved address mapping(uint256 => address) internal approvals; // Mapping of owner => operator => approved mapping(address => mapping(address => bool)) internal operatorApprovals; // ** end ERC721 constructor( LavaToken _lava, uint256 _lavaPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { lava = _lava; lavaPerBlock = _lavaPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); } function sacredGroveLength() external view returns (uint256) { return sacredGrove.length; } // Add a new sacred grove. Can only be called by god!! function addSacredGrove(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyGod { require(!isSacredGrove[address(_lpToken)], "This is already a known sacred grove"); if (_withUpdate) { massUpdateSacredGroves(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); sacredGrove.push(SacredGrove({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accLavaPerShare : 0, totalSupply : 0, endBlock : 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff })); isSacredGrove[address(_lpToken)] = true; } // Update the given grove's allocation point. Can only be called by the owner. function set(uint256 _groveId, uint256 _allocPoint, bool _withUpdate) public onlyGod { if (_withUpdate) { massUpdateSacredGroves(); } totalAllocPoint = totalAllocPoint.sub(sacredGrove[_groveId].allocPoint).add(_allocPoint); sacredGrove[_groveId].allocPoint = _allocPoint; } function end(uint256 _groveId, uint256 _endBlock, bool _withUpdate) public onlyGod { SacredGrove storage grove = sacredGrove[_groveId]; grove.endBlock = _endBlock; if (_withUpdate) { massUpdateSacredGroves(); } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock)); } } function thunderEggStats(uint256 _groveId, uint256 _eggId) external view returns (address _owner, uint256 _birth, uint256 _age, uint256 _lp, uint256 _lava, bytes32 _name) { if (!_exists(_eggId)) { return (address(0x0), 0, 0, 0, 0, bytes32(0x0)); } ThunderEggInfo storage info = thunderEggInfoMapping[_groveId][_eggId]; return ( thunderEggIdToOwner[_eggId], thunderEggIdToBirth[_eggId], block.number - thunderEggIdToBirth[_eggId], info.amount, _calculatePendingLava(_groveId, _eggId), thunderEggIdToName[_eggId] ); } // View function to see pending LAVAs on frontend. function pendingLava(uint256 _groveId, uint256 _eggId) external view returns (uint256) { // no ThunderEgg, no lava! if (!_exists(_eggId)) { return 0; } return _calculatePendingLava(_groveId, _eggId); } function _calculatePendingLava(uint256 _groveId, uint256 _eggId) internal view returns (uint256) { SacredGrove storage grove = sacredGrove[_groveId]; ThunderEggInfo storage info = thunderEggInfoMapping[_groveId][_eggId]; uint256 accLavaPerShare = grove.accLavaPerShare; uint256 lpSupply = grove.lpToken.balanceOf(address(this)); if (block.number > grove.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(grove.lastRewardBlock, block.number <= grove.endBlock ? block.number : grove.endBlock); uint256 lavaReward = multiplier.mul(lavaPerBlock).mul(grove.allocPoint).div(totalAllocPoint); accLavaPerShare = accLavaPerShare.add(lavaReward.mul(1e18).div(lpSupply)); } return info.amount.mul(accLavaPerShare).div(1e18).sub(info.rewardDebt); } // Update reward variables for all grove. Be careful of gas spending! function massUpdateSacredGroves() public { uint256 length = sacredGrove.length; for (uint256 groveId = 0; groveId < length; ++groveId) { updateSacredGrove(groveId); } } // Update reward variables of the given grove to be up-to-date. function updateSacredGrove(uint256 _groveId) public { SacredGrove storage grove = sacredGrove[_groveId]; if (block.number <= grove.lastRewardBlock) { return; } uint256 lpSupply = grove.lpToken.balanceOf(address(this)); if (lpSupply == 0) { grove.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(grove.lastRewardBlock, block.number <= grove.endBlock ? block.number : grove.endBlock); uint256 lavaReward = multiplier.mul(lavaPerBlock).mul(grove.allocPoint).div(totalAllocPoint); // offering to the gods lava.mint(god(), lavaReward.div(godsOffering)); // reward for ThunderEggs lava.mint(address(this), lavaReward); grove.accLavaPerShare = grove.accLavaPerShare.add(lavaReward.mul(1e18).div(lpSupply)); grove.lastRewardBlock = block.number; } // mint the ThunderEgg by depositing LP tokens, function spawn(uint256 _groveId, uint256 _amount, bytes32 _name) public { require(ownerToThunderEggId[msg.sender] == 0, "Thor has already blessed you with a ThunderEgg!"); require(_amount > 0, "You must sacrifice your LP tokens to the gods!"); updateSacredGrove(_groveId); // Thunder 🥚 time! uint256 eggId = _mint(_groveId, msg.sender, _name); SacredGrove storage pool = sacredGrove[_groveId]; ThunderEggInfo storage info = thunderEggInfoMapping[_groveId][eggId]; // credit the staked amount pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); info.amount = info.amount.add(_amount); info.rewardDebt = info.amount.mul(pool.accLavaPerShare).div(1e18); emit Deposit(msg.sender, _groveId, _amount); } // Destroy and get all the tokens back - bye bye NFT! function destroy(uint256 _groveId) public { uint256 eggId = ownerToThunderEggId[msg.sender]; require(eggId != 0, "No ThunderEgg!"); updateSacredGrove(_groveId); SacredGrove storage pool = sacredGrove[_groveId]; ThunderEggInfo storage info = thunderEggInfoMapping[_groveId][eggId]; // burn the token - send all rewards and LP back! _burn(_groveId, eggId); // pay out rewards from the ThunderEgg uint256 pending = info.amount.mul(pool.accLavaPerShare).div(1e18).sub(info.rewardDebt); if (pending > 0) { safeLavaTransfer(msg.sender, pending); } // send all LP back... pool.lpToken.safeTransfer(address(msg.sender), info.amount); info.rewardDebt = info.amount.mul(pool.accLavaPerShare).div(1e18); emit Withdraw(msg.sender, _groveId, info.amount); } // Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. function safeLavaTransfer(address _to, uint256 _amount) internal { uint256 lavaBal = lava.balanceOf(address(this)); if (_amount > lavaBal) { lava.transfer(_to, lavaBal); } else { lava.transfer(_to, _amount); } } // *** ERC721 functions below 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 _checkOnERC721Received(address from, address to, uint256 eggId, bytes memory _data) private returns (bool) { if (!isContract(to)) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, msg.sender, from, eggId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == ERC721_RECEIVED); } return true; } function setGodsOffering(uint256 _godsOffering) external onlyGod { godsOffering = _godsOffering; } function setBaseTokenURI(string calldata _uri) external onlyGod { baseTokenURI = _uri; } function setName(uint256 _eggId, bytes32 _name) external onlyGod { thunderEggIdToName[_eggId] = _name; } function _mint(uint256 _groveId, address _to, bytes32 _name) internal returns (uint256) { require(_to != address(0), "ERC721: mint to the zero address"); SacredGrove storage grove = sacredGrove[_groveId]; require(grove.endBlock >= block.number, 'This grove is not longer fertile'); tokenPointer = tokenPointer.add(1); uint256 eggId = tokenPointer; // Mint thunderEggIdToOwner[eggId] = _to; ownerToThunderEggId[msg.sender] = eggId; // birth thunderEggIdToBirth[eggId] = block.number; // name thunderEggIdToName[eggId] = _name; // MetaData grove.totalSupply = grove.totalSupply.add(1); totalSupply = totalSupply.add(1); totalSpawned = totalSpawned.add(1); // Single Transfer event for a single token emit Transfer(address(0), _to, eggId); return eggId; } function exists(uint256 _eggId) external view returns (bool) { return _exists(_eggId); } function _exists(uint256 _eggId) internal view returns (bool) { return thunderEggIdToOwner[_eggId] != address(0); } function tokenURI(uint256 _eggId) external view returns (string memory) { require(_exists(_eggId), "ERC721Metadata: URI query for nonexistent token"); return Strings.strConcat(baseTokenURI, Strings.uint2str(_eggId)); } function _burn(uint256 _groveId, uint256 _eggId) internal { require(_exists(_eggId), "must exist"); address owner = thunderEggIdToOwner[_eggId]; require(owner == msg.sender, "Must own the egg!"); SacredGrove storage pool = sacredGrove[_groveId]; thunderEggIdToOwner[_eggId] = address(0); ownerToThunderEggId[msg.sender] = 0; pool.totalSupply = pool.totalSupply.sub(1); totalSupply = totalSupply.sub(1); totalDestroyed = totalDestroyed.add(1); emit Transfer( owner, address(0), _eggId ); } function safeTransferFrom(address _from, address _to, uint256 _eggId) override public { safeTransferFrom(_from, _to, _eggId, ""); } function safeTransferFrom(address _from, address _to, uint256 _eggId, bytes memory _data) override public { transferFrom(_from, _to, _eggId); require(_checkOnERC721Received(_from, _to, _eggId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } function approve(address _approved, uint256 _eggId) override external { address owner = ownerOf(_eggId); require(_approved != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); approvals[_eggId] = _approved; emit Approval( owner, _approved, _eggId ); } function setApprovalForAll(address _operator, bool _approved) override external { require(_operator != msg.sender, "ERC721: approve to caller"); operatorApprovals[msg.sender][_operator] = _approved; emit ApprovalForAll( msg.sender, _operator, _approved ); } function balanceOf(address _owner) override external view returns (uint256) { require(_owner != address(0), "ERC721: balance query for the zero address"); return ownerToThunderEggId[_owner] != 0 ? 1 : 0; } function transferFrom(address _from, address _to, uint256 _eggId) override public { require( _to != address(0), "ERC721: transfer to the zero address" ); address owner = ownerOf(_eggId); require( _from == owner, "ERC721: transfer of token that is not own" ); address spender = msg.sender; address approvedAddress = getApproved(_eggId); require( spender == owner || isApprovedForAll(owner, spender) || approvedAddress == spender, "ERC721: transfer caller is not owner nor approved" ); if (approvedAddress != address(0)) { approvals[_eggId] = address(0); } emit Approval(owner, address(0), _eggId); thunderEggIdToOwner[_eggId] = _to; ownerToThunderEggId[_from] = 0; ownerToThunderEggId[_to] = _eggId; emit Transfer( _from, _to, _eggId ); } function ownerOf(uint256 _eggId) override public view returns (address) { require(_exists(_eggId), "ERC721: operator query for nonexistent token"); return thunderEggIdToOwner[_eggId]; } function getApproved(uint256 _eggId) override public view returns (address) { require(_exists(_eggId), "ERC721: approved query for nonexistent token"); return approvals[_eggId]; } function isApprovedForAll(address _owner, address _operator) override public view returns (bool) { return operatorApprovals[_owner][_operator]; } } contract MockERC20 is ERC20 { constructor( string memory name, string memory symbol, uint256 supply ) public ERC20(name, symbol) { _mint(msg.sender, supply); } function mint(address _to, uint256 _amount) public { _mint(_to, _amount); } }
0x608060405234801561001057600080fd5b506004361061028a5760003560e01c80634f558e791161015c578063a22cb465116100ce578063d4d1468411610087578063d4d1468414610890578063d547cfb7146108b6578063d6ed7bf1146108be578063e3721a23146108c6578063e382c85814610902578063e985e9c51461092b5761028a565b8063a22cb46514610749578063b72ba6b514610777578063b88d4fde1461077f578063b93391ee14610845578063ba56f6ee1461086b578063c87b56dd146108735761028a565b8063814e067911610120578063814e0679146106b05780638aa28550146106d65780638dbb1e3a146106de57806395d89b41146107015780639d11877014610709578063a12396aa146107265761028a565b80634f558e79146106025780636352211e1461061f57806364482f791461063c5780636fd873191461066757806370a082311461068a5761028a565b80631f11d110116102005780633fb06f1c116101b95780633fb06f1c1461056c57806342842e0e1461058957806348cd4cb1146105bf5780634b07a274146105c75780634da24826146105cf5780634efa55e7146105d75761028a565b80631f11d1101461046557806323b872dd1461046d5780632cc11a23146104a357806330176e13146104c05780633368ee4814610530578063364a7db9146105385761028a565b80630cba3772116102525780630cba3772146103c857806310b5b2a01461042857806317809b171461044557806317caf6f11461044d57806318160ddd146104555780631aed65531461045d5761028a565b806301ffc9a71461028f57806302831651146102ca57806306fdde03146102e4578063081812fc14610361578063095ea7b31461039a575b600080fd5b6102b6600480360360208110156102a557600080fd5b50356001600160e01b031916610959565b604080519115158252519081900360200190f35b6102d261097c565b60408051918252519081900360200190f35b6102ec610982565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561032657818101518382015260200161030e565b50505050905090810190601f1680156103535780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61037e6004803603602081101561037757600080fd5b5035610a10565b604080516001600160a01b039092168252519081900360200190f35b6103c6600480360360408110156103b057600080fd5b506001600160a01b038135169060200135610a72565b005b6103eb600480360360408110156103de57600080fd5b5080359060200135610b83565b604080516001600160a01b0390971687526020870195909552858501939093526060850191909152608084015260a0830152519081900360c00190f35b6103c66004803603602081101561043e57600080fd5b5035610c20565b61037e610c72565b6102d2610c81565b6102d2610c87565b6102d2610c8d565b6102d2610c93565b6103c66004803603606081101561048357600080fd5b506001600160a01b03813581169160208101359091169060400135610c99565b6103c6600480360360208110156104b957600080fd5b5035610ea3565b6103c6600480360360208110156104d657600080fd5b8101906020810181356401000000008111156104f157600080fd5b82018360208201111561050357600080fd5b8035906020019184600183028401116401000000008311171561052557600080fd5b5090925090506110ed565b6102d261114b565b6103c66004803603606081101561054e57600080fd5b508035906001600160a01b0360208201351690604001351515611151565b6103eb6004803603602081101561058257600080fd5b5035611395565b6103c66004803603606081101561059f57600080fd5b506001600160a01b038135811691602081013590911690604001356113e2565b6102d26113fd565b6102d2611403565b6103c6611409565b6103c6600480360360608110156105ed57600080fd5b5080359060208101359060400135151561142c565b6102b66004803603602081101561061857600080fd5b50356114b5565b61037e6004803603602081101561063557600080fd5b50356114c6565b6103c66004803603606081101561065257600080fd5b50803590602081013590604001351515611528565b6102d26004803603604081101561067d57600080fd5b50803590602001356115ee565b6102d2600480360360208110156106a057600080fd5b50356001600160a01b0316611616565b6102b6600480360360208110156106c657600080fd5b50356001600160a01b031661168d565b6102d26116a2565b6102d2600480360360408110156106f457600080fd5b50803590602001356116a7565b6102ec61170d565b6103c66004803603602081101561071f57600080fd5b5035611768565b6103c66004803603604081101561073c57600080fd5b50803590602001356118cb565b6103c66004803603604081101561075f57600080fd5b506001600160a01b038135169060200135151561192a565b6102d26119f6565b6103c66004803603608081101561079557600080fd5b6001600160a01b038235811692602081013590911691604082013591908101906080810160608201356401000000008111156107d057600080fd5b8201836020820111156107e257600080fd5b8035906020019184600183028401116401000000008311171561080457600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295506119fc945050505050565b6102d26004803603602081101561085b57600080fd5b50356001600160a01b0316611a4e565b61037e611a60565b6102ec6004803603602081101561088957600080fd5b5035611a6f565b6103c6600480360360208110156108a657600080fd5b50356001600160a01b0316611b55565b6102ec611c42565b6102d2611c9d565b6108e9600480360360408110156108dc57600080fd5b5080359060200135611ca3565b6040805192835260208301919091528051918290030190f35b6103c66004803603606081101561091857600080fd5b5080359060208101359060400135611cc7565b6102b66004803603604081101561094157600080fd5b506001600160a01b0381358116916020013516611e29565b6001600160e01b0319811660009081526001602052604090205460ff165b919050565b600c5481565b600d805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610a085780601f106109dd57610100808354040283529160200191610a08565b820191906000526020600020905b8154815290600101906020018083116109eb57829003601f168201915b505050505081565b6000610a1b82611e57565b610a565760405162461bcd60e51b815260040180806020018281038252602c8152602001806130c2602c913960400191505060405180910390fd5b506000908152601660205260409020546001600160a01b031690565b6000610a7d826114c6565b9050806001600160a01b0316836001600160a01b03161415610ad05760405162461bcd60e51b81526004018080602001828103825260218152602001806131956021913960400191505060405180910390fd5b336001600160a01b0382161480610aec5750610aec8133611e29565b610b275760405162461bcd60e51b815260040180806020018281038252603881526020018061303f6038913960400191505060405180910390fd5b60008281526016602052604080822080546001600160a01b0319166001600160a01b0387811691821790925591518593918516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591a4505050565b600080600080600080610b9587611e57565b610bb057506000945084935083925082915081905080610c16565b60008881526007602090815260408083208a845282528083206012835281842054601390935292205482546001600160a01b03909216914382900390610bf68d8d611e74565b60008d815260146020526040902054949b50929950909750955093509150505b9295509295509295565b6000546001600160a01b03163314610c6d576040805162461bcd60e51b815260206004820152601e6024820152600080516020613175833981519152604482015290519081900360640190fd5b600555565b6002546001600160a01b031681565b60085481565b600f5481565b60035481565b60065490565b6001600160a01b038216610cde5760405162461bcd60e51b8152600401808060200182810382526024815260200180612fef6024913960400191505060405180910390fd5b6000610ce9826114c6565b9050806001600160a01b0316846001600160a01b031614610d3b5760405162461bcd60e51b81526004018080602001828103825260298152602001806130ee6029913960400191505060405180910390fd5b336000610d4784610a10565b9050826001600160a01b0316826001600160a01b03161480610d6e5750610d6e8383611e29565b80610d8a5750816001600160a01b0316816001600160a01b0316145b610dc55760405162461bcd60e51b81526004018080602001828103825260318152602001806131b66031913960400191505060405180910390fd5b6001600160a01b03811615610df157600084815260166020526040902080546001600160a01b03191690555b60405184906000906001600160a01b038616907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925908390a4600084815260126020908152604080832080546001600160a01b0319166001600160a01b038a8116918217909255908a168085526015909352818420849055808452818420889055905187939192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050505050565b600060068281548110610eb257fe5b9060005260206000209060060201905080600201544311610ed357506110ea565b8054604080516370a0823160e01b815230600482015290516000926001600160a01b0316916370a08231916024808301926020929190829003018186803b158015610f1d57600080fd5b505afa158015610f31573d6000803e3d6000fd5b505050506040513d6020811015610f4757600080fd5b5051905080610f5d5750436002909101556110ea565b6000610f8483600201548460050154431115610f7d578460050154610f7f565b435b6116a7565b90506000610fb7600854610fb18660010154610fab60045487611fe690919063ffffffff16565b90611fe6565b9061203f565b6002549091506001600160a01b03166340c10f19610fd3611a60565b600554610fe190859061203f565b6040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561102757600080fd5b505af115801561103b573d6000803e3d6000fd5b5050600254604080516340c10f1960e01b81523060048201526024810186905290516001600160a01b0390921693506340c10f19925060448082019260009290919082900301818387803b15801561109257600080fd5b505af11580156110a6573d6000803e3d6000fd5b505050506110d76110cc84610fb1670de0b6b3a764000085611fe690919063ffffffff16565b600386015490612081565b6003850155505043600290920191909155505b50565b6000546001600160a01b0316331461113a576040805162461bcd60e51b815260206004820152601e6024820152600080516020613175833981519152604482015290519081900360640190fd5b611146600b8383612f29565b505050565b60115481565b6000546001600160a01b0316331461119e576040805162461bcd60e51b815260206004820152601e6024820152600080516020613175833981519152604482015290519081900360640190fd5b6001600160a01b0382166000908152600a602052604090205460ff16156111f65760405162461bcd60e51b81526004018080602001828103825260248152602001806132656024913960400191505060405180910390fd5b801561120457611204611409565b6000600954431161121757600954611219565b435b6008549091506112299085612081565b6008556040805160c0810182526001600160a01b0394851680825260208083019788528284019485526000606084018181526080850182815260001960a087019081526006805460018181018355828752985191027ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f8101805492909d166001600160a01b031990921691909117909b559a517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d408b015596517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d418a0155517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d4289015594517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d4388015596517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d4490960195909555938252600a90945292909220805460ff1916909117905550565b600681815481106113a257fe5b60009182526020909120600690910201805460018201546002830154600384015460048501546005909501546001600160a01b0390941695509193909286565b611146838383604051806020016040528060008152506119fc565b60095481565b60055481565b60065460005b818110156114285761142081610ea3565b60010161140f565b5050565b6000546001600160a01b03163314611479576040805162461bcd60e51b815260206004820152601e6024820152600080516020613175833981519152604482015290519081900360640190fd5b60006006848154811061148857fe5b9060005260206000209060060201905082816005018190555081156114af576114af611409565b50505050565b60006114c082611e57565b92915050565b60006114d182611e57565b61150c5760405162461bcd60e51b815260040180806020018281038252602c815260200180613013602c913960400191505060405180910390fd5b506000908152601260205260409020546001600160a01b031690565b6000546001600160a01b03163314611575576040805162461bcd60e51b815260206004820152601e6024820152600080516020613175833981519152604482015290519081900360640190fd5b801561158357611583611409565b6115c0826115ba6006868154811061159757fe5b9060005260206000209060060201600101546008546120db90919063ffffffff16565b90612081565b60088190555081600684815481106115d457fe5b906000526020600020906006020160010181905550505050565b60006115f982611e57565b611605575060006114c0565b61160f8383611e74565b9392505050565b60006001600160a01b03821661165d5760405162461bcd60e51b815260040180806020018281038252602a815260200180613077602a913960400191505060405180910390fd5b6001600160a01b038216600090815260156020526040902054611681576000611684565b60015b60ff1692915050565b600a6020526000908152604090205460ff1681565b600a81565b600060035482116116c8576116c1600a610fab84866120db565b90506114c0565b60035483106116db576116c182846120db565b6116c16116f3600354846120db90919063ffffffff16565b6115ba600a610fab876003546120db90919063ffffffff16565b600e805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610a085780601f106109dd57610100808354040283529160200191610a08565b33600090815260156020526040902054806117bb576040805162461bcd60e51b815260206004820152600e60248201526d4e6f205468756e6465724567672160901b604482015290519081900360640190fd5b6117c482610ea3565b6000600683815481106117d357fe5b60009182526020808320868452600782526040808520878652909252922060069091029091019150611805848461211d565b600061183c8260010154611836670de0b6b3a7640000610fb187600301548760000154611fe690919063ffffffff16565b906120db565b9050801561184e5761184e3382612282565b81548354611869916001600160a01b03909116903390612412565b6003830154825461188791670de0b6b3a764000091610fb191611fe6565b600183015581546040805191825251869133917ff279e6a1f5e320cca91135676d9cb6e44ca8a08c0b88342bcdb1144f6511b5689181900360200190a35050505050565b6000546001600160a01b03163314611918576040805162461bcd60e51b815260206004820152601e6024820152600080516020613175833981519152604482015290519081900360640190fd5b60009182526014602052604090912055565b6001600160a01b038216331415611988576040805162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c657200000000000000604482015290519081900360640190fd5b3360008181526017602090815260408083206001600160a01b03871680855290835292819020805460ff1916861515908117909155815190815290519293927f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31929181900390910190a35050565b60105481565b611a07848484610c99565b611a1384848484612464565b6114af5760405162461bcd60e51b8152600401808060200182810382526032815260200180612fbd6032913960400191505060405180910390fd5b60156020526000908152604090205481565b6000546001600160a01b031690565b6060611a7a82611e57565b611ab55760405162461bcd60e51b815260040180806020018281038252602f815260200180613146602f913960400191505060405180910390fd5b600b8054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526114c09390929091830182828015611b425780601f10611b1757610100808354040283529160200191611b42565b820191906000526020600020905b815481529060010190602001808311611b2557829003601f168201915b5050505050611b5084612685565b61275d565b6000546001600160a01b03163314611ba2576040805162461bcd60e51b815260206004820152601e6024820152600080516020613175833981519152604482015290519081900360640190fd5b6001600160a01b038116611be75760405162461bcd60e51b81526004018080602001828103825260268152602001806131e76026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b600b805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610a085780601f106109dd57610100808354040283529160200191610a08565b60045481565b60076020908152600092835260408084209091529082529020805460019091015482565b3360009081526015602052604090205415611d135760405162461bcd60e51b815260040180806020018281038252602f815260200180613117602f913960400191505060405180910390fd5b60008211611d525760405162461bcd60e51b815260040180806020018281038252602e815260200180613237602e913960400191505060405180910390fd5b611d5b83610ea3565b6000611d68843384612799565b9050600060068581548110611d7957fe5b60009182526020808320888452600782526040808520878652909252922060069091029091018054909250611db9906001600160a01b0316333088612947565b8054611dc59086612081565b8082556003830154611de591670de0b6b3a764000091610fb19190611fe6565b6001820155604080518681529051879133917f90890809c654f11d6e72a28fa60149770a0d11ec6c92319d6ceb2bb0a4ea1a159181900360200190a3505050505050565b6001600160a01b03918216600090815260176020908152604080832093909416825291909152205460ff1690565b6000908152601260205260409020546001600160a01b0316151590565b60008060068481548110611e8457fe5b6000918252602080832087845260078252604080852088865283528085206003600690950290920193840154845482516370a0823160e01b815230600482015292519597509295909490936001600160a01b03909316926370a082319260248082019391829003018186803b158015611efc57600080fd5b505afa158015611f10573d6000803e3d6000fd5b505050506040513d6020811015611f2657600080fd5b5051600285015490915043118015611f3d57508015155b15611fb0576000611f6285600201548660050154431115610f7d578660050154610f7f565b90506000611f89600854610fb18860010154610fab60045487611fe690919063ffffffff16565b9050611fab611fa484610fb184670de0b6b3a7640000611fe6565b8590612081565b935050505b611fdb8360010154611836670de0b6b3a7640000610fb1868860000154611fe690919063ffffffff16565b979650505050505050565b600082611ff5575060006114c0565b8282028284828161200257fe5b041461160f5760405162461bcd60e51b81526004018080602001828103825260218152602001806130a16021913960400191505060405180910390fd5b600061160f83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f0000000000008152506129a1565b60008282018381101561160f576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600061160f83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612a43565b61212681611e57565b612164576040805162461bcd60e51b815260206004820152600a6024820152691b5d5cdd08195e1a5cdd60b21b604482015290519081900360640190fd5b6000818152601260205260409020546001600160a01b03163381146121c4576040805162461bcd60e51b81526020600482015260116024820152704d757374206f776e20746865206567672160781b604482015290519081900360640190fd5b6000600684815481106121d357fe5b6000918252602080832086845260128252604080852080546001600160a01b031916905533855260159092529083209290925560060201600481015490915061221d9060016120db565b6004820155600f546122309060016120db565b600f55601154612241906001612081565b60115560405183906000906001600160a01b038516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908390a450505050565b600254604080516370a0823160e01b815230600482015290516000926001600160a01b0316916370a08231916024808301926020929190829003018186803b1580156122cd57600080fd5b505afa1580156122e1573d6000803e3d6000fd5b505050506040513d60208110156122f757600080fd5b505190508082111561238b576002546040805163a9059cbb60e01b81526001600160a01b038681166004830152602482018590529151919092169163a9059cbb9160448083019260209291908290030181600087803b15801561235957600080fd5b505af115801561236d573d6000803e3d6000fd5b505050506040513d602081101561238357600080fd5b506111469050565b6002546040805163a9059cbb60e01b81526001600160a01b038681166004830152602482018690529151919092169163a9059cbb9160448083019260209291908290030181600087803b1580156123e157600080fd5b505af11580156123f5573d6000803e3d6000fd5b505050506040513d602081101561240b57600080fd5b5050505050565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052611146908490612a9d565b600061246f84612b4e565b61247b5750600161267d565b60006060856001600160a01b031663150b7a0260e01b3389888860405160240180856001600160a01b03168152602001846001600160a01b0316815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b838110156124f95781810151838201526020016124e1565b50505050905090810190601f1680156125265780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529181526020820180516001600160e01b03166001600160e01b0319909a16999099178952518151919890975087965094509250829150849050835b6020831061258e5780518252601f19909201916020918201910161256f565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146125f0576040519150601f19603f3d011682016040523d82523d6000602084013e6125f5565b606091505b5091509150816126465780511561260f5780518082602001fd5b60405162461bcd60e51b8152600401808060200182810382526032815260200180612fbd6032913960400191505060405180910390fd5b600081806020019051602081101561265d57600080fd5b50516001600160e01b031916630a85bd0160e11b14935061267d92505050565b949350505050565b6060816126aa57506040805180820190915260018152600360fc1b6020820152610977565b8160005b81156126c257600101600a820491506126ae565b60608167ffffffffffffffff811180156126db57600080fd5b506040519080825280601f01601f191660200182016040528015612706576020820181803683370190505b50905060001982015b851561275457600a860660300160f81b8282806001900393508151811061273257fe5b60200101906001600160f81b031916908160001a905350600a8604955061270f565b50949350505050565b606061160f8383604051806020016040528060008152506040518060200160405280600081525060405180602001604052806000815250612b87565b60006001600160a01b0383166127f6576040805162461bcd60e51b815260206004820181905260248201527f4552433732313a206d696e7420746f20746865207a65726f2061646472657373604482015290519081900360640190fd5b60006006858154811061280557fe5b90600052602060002090600602019050438160050154101561286e576040805162461bcd60e51b815260206004820181905260248201527f546869732067726f7665206973206e6f74206c6f6e6765722066657274696c65604482015290519081900360640190fd5b600c5461287c906001612081565b600c819055600081815260126020908152604080832080546001600160a01b0319166001600160a01b038a1617905533835260158252808320849055838352601382528083204390556014909152902084905560048201546128df906001612081565b6004830155600f546128f2906001612081565b600f55601054612903906001612081565b60105560405181906001600160a01b038716906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a495945050505050565b604080516001600160a01b0380861660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b1790526114af908590612a9d565b60008183612a2d5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156129f25781810151838201526020016129da565b50505050905090810190601f168015612a1f5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581612a3957fe5b0495945050505050565b60008184841115612a955760405162461bcd60e51b81526020600482018181528351602484015283519092839260449091019190850190808383600083156129f25781810151838201526020016129da565b505050900390565b6060612af2826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612dac9092919063ffffffff16565b80519091501561114657808060200190516020811015612b1157600080fd5b50516111465760405162461bcd60e51b815260040180806020018281038252602a81526020018061320d602a913960400191505060405180910390fd5b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061267d575050151592915050565b805182518451865188516060948a948a948a948a948a948a94919092019092019091010167ffffffffffffffff81118015612bc157600080fd5b506040519080825280601f01601f191660200182016040528015612bec576020820181803683370190505b509050806000805b8851811015612c4557888181518110612c0957fe5b602001015160f81c60f81b838380600101945081518110612c2657fe5b60200101906001600160f81b031916908160001a905350600101612bf4565b5060005b8751811015612c9a57878181518110612c5e57fe5b602001015160f81c60f81b838380600101945081518110612c7b57fe5b60200101906001600160f81b031916908160001a905350600101612c49565b5060005b8651811015612cef57868181518110612cb357fe5b602001015160f81c60f81b838380600101945081518110612cd057fe5b60200101906001600160f81b031916908160001a905350600101612c9e565b5060005b8551811015612d4457858181518110612d0857fe5b602001015160f81c60f81b838380600101945081518110612d2557fe5b60200101906001600160f81b031916908160001a905350600101612cf3565b5060005b8451811015612d9957848181518110612d5d57fe5b602001015160f81c60f81b838380600101945081518110612d7a57fe5b60200101906001600160f81b031916908160001a905350600101612d48565b50909d9c50505050505050505050505050565b606061267d84846000856060612dc185612f23565b612e12576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b60208310612e515780518252601f199092019160209182019101612e32565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d8060008114612eb3576040519150601f19603f3d011682016040523d82523d6000602084013e612eb8565b606091505b50915091508115612ecc57915061267d9050565b805115612edc5780518082602001fd5b60405162461bcd60e51b81526020600482018181528651602484015286518793919283926044019190850190808383600083156129f25781810151838201526020016129da565b3b151590565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10612f6a5782800160ff19823516178555612f97565b82800160010185558215612f97579182015b82811115612f97578235825591602001919060010190612f7c565b50612fa3929150612fa7565b5090565b5b80821115612fa35760008155600101612fa856fe4552433732313a207472616e7366657220746f206e6f6e20455243373231526563656976657220696d706c656d656e7465724552433732313a207472616e7366657220746f20746865207a65726f20616464726573734552433732313a206f70657261746f7220717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a20617070726f76652063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f76656420666f7220616c6c4552433732313a2062616c616e636520717565727920666f7220746865207a65726f2061646472657373536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f774552433732313a20617070726f76656420717565727920666f72206e6f6e6578697374656e7420746f6b656e4552433732313a207472616e73666572206f6620746f6b656e2074686174206973206e6f74206f776e54686f722068617320616c726561647920626c657373656420796f7520776974682061205468756e646572456767214552433732314d657461646174613a2055524920717565727920666f72206e6f6e6578697374656e7420746f6b656e476f6461626c653a2063616c6c6572206973206e6f742074686520676f6400004552433732313a20617070726f76616c20746f2063757272656e74206f776e65724552433732313a207472616e736665722063616c6c6572206973206e6f74206f776e6572206e6f7220617070726f766564476f6461626c653a206e6577206f776e657220697320746865207a65726f20616464726573735361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564596f75206d7573742073616372696669636520796f7572204c5020746f6b656e7320746f2074686520676f6473215468697320697320616c72656164792061206b6e6f776e207361637265642067726f7665a264697066735822122067b0c69cc3b6435496ab202f3be09b2025c1bdf854cf6917e3708810e68e38d964736f6c634300060c0033
[ 4, 7, 37, 9, 16 ]
0x4f540B7E7FCb5d8a1d540fD5c1852bacE3BC1893
pragma solidity 0.5.17; contract ERC20 { using SafeMath for uint256; mapping(address => uint256) private _balances; uint256 private _totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev 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) { _transfer(from, to, value); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer( address from, address to, uint256 value ) internal { require(value <= _balances[from]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } } contract MyERC20 is ERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap ) public { _name = name; _symbol = symbol; _decimals = decimals; super._mint(msg.sender, cap); } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
0x608060405234801561001057600080fd5b506004361061007d5760003560e01c8063313ce5671161005b578063313ce5671461016357806370a082311461018157806395d89b41146101a7578063a9059cbb146101af5761007d565b806306fdde031461008257806318160ddd146100ff57806323b872dd14610119575b600080fd5b61008a6101db565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100c45781810151838201526020016100ac565b50505050905090810190601f1680156100f15780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61010761026e565b60408051918252519081900360200190f35b61014f6004803603606081101561012f57600080fd5b506001600160a01b03813581169160208101359091169060400135610274565b604080519115158252519081900360200190f35b61016b61028b565b6040805160ff9092168252519081900360200190f35b6101076004803603602081101561019757600080fd5b50356001600160a01b0316610294565b61008a6102af565b61014f600480360360408110156101c557600080fd5b506001600160a01b038135169060200135610310565b60028054604080516020601f60001961010060018716150201909416859004938401819004810282018101909252828152606093909290918301828280156102645780601f1061023957610100808354040283529160200191610264565b820191906000526020600020905b81548152906001019060200180831161024757829003601f168201915b5050505050905090565b60015490565b6000610281848484610326565b5060019392505050565b60045460ff1690565b6001600160a01b031660009081526020819052604090205490565b60038054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156102645780601f1061023957610100808354040283529160200191610264565b600061031d338484610326565b50600192915050565b6001600160a01b03831660009081526020819052604090205481111561034b57600080fd5b6001600160a01b03821661035e57600080fd5b6001600160a01b038316600090815260208190526040902054610387908263ffffffff61041616565b6001600160a01b0380851660009081526020819052604080822093909355908416815220546103bc908263ffffffff61042b16565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008282111561042557600080fd5b50900390565b60008282018381101561043d57600080fd5b9392505050565b6001600160a01b03821661045757600080fd5b60015461046a908263ffffffff61042b16565b6001556001600160a01b038216600090815260208190526040902054610496908263ffffffff61042b16565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a3505056fea265627a7a72315820b01292331d562ceb5130a806057a53f7c76501de5b4549eff0229aa9aaf581d164736f6c63430005110032
[ 38 ]
0x4fd2d9d6ef05e13bf0b167509151a4ec3d4d4b93
pragma solidity 0.5.12; contract BColor { function getColor() external view returns (bytes32); } contract BBronze is BColor { function getColor() external view returns (bytes32) { return bytes32("BRONZE"); } } contract BConst is BBronze { uint public constant BONE = 10**18; uint public constant MIN_BOUND_TOKENS = 2; uint public constant MAX_BOUND_TOKENS = 8; uint public constant MIN_FEE = BONE / 10**6; uint public constant MAX_FEE = BONE / 10; uint public constant EXIT_FEE = 0; uint public constant DEFAULT_RESERVES_RATIO = BONE / 5; uint public constant MIN_WEIGHT = BONE; uint public constant MAX_WEIGHT = BONE * 50; uint public constant MAX_TOTAL_WEIGHT = BONE * 50; uint public constant MIN_BALANCE = BONE / 10**12; uint public constant INIT_POOL_SUPPLY = BONE * 100; uint public constant MIN_BPOW_BASE = 1 wei; uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei; uint public constant BPOW_PRECISION = BONE / 10**10; uint public constant MAX_IN_RATIO = BONE / 2; uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei; } contract BNum is BConst { function btoi(uint a) internal pure returns (uint) { return a / BONE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BONE; } function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b); uint c1 = c0 + (BONE / 2); require(c1 >= c0); uint c2 = c1 / BONE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0); uint c0 = a * BONE; require(a == 0 || c0 / a == BONE); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0); // badd require uint c2 = c1 / b; return c2; } // DSMath.wpow function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BONE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } // Compute b^(e.w) by splitting it into (b^e)*(b^0.w). // Use `bpowi` for `b^e` and `bpowK` for k iterations // of approximation of b^0.w function bpow(uint base, uint exp) internal pure returns (uint) { require(base >= MIN_BPOW_BASE); require(base <= MAX_BPOW_BASE); uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BONE); uint term = BONE; uint sum = term; bool negative = false; // term(k) = numer / denom // = (product(a - i - 1, i=1-->k) * x^k) / (k!) // each iteration, multiply previous term by (a-(k-1)) * x / k // continue until term is less than precision for (uint i = 1; term >= precision; i++) { uint bigK = i * BONE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } interface IERC20 { event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function totalSupply() external view returns (uint); function balanceOf(address whom) external view returns (uint); function allowance(address src, address dst) external view returns (uint); function approve(address dst, uint amt) external returns (bool); function transfer(address dst, uint amt) external returns (bool); function transferFrom( address src, address dst, uint amt ) external returns (bool); } contract BTokenBase is BNum { mapping(address => uint) internal _balance; mapping(address => mapping(address=>uint)) internal _allowance; uint internal _totalSupply; event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function _mint(uint amt) internal { _balance[address(this)] = badd(_balance[address(this)], amt); _totalSupply = badd(_totalSupply, amt); emit Transfer(address(0), address(this), amt); } function _burn(uint amt) internal { require(_balance[address(this)] >= amt); _balance[address(this)] = bsub(_balance[address(this)], amt); _totalSupply = bsub(_totalSupply, amt); emit Transfer(address(this), address(0), amt); } function _move(address src, address dst, uint amt) internal { require(_balance[src] >= amt); _balance[src] = bsub(_balance[src], amt); _balance[dst] = badd(_balance[dst], amt); emit Transfer(src, dst, amt); } function _push(address to, uint amt) internal { _move(address(this), to, amt); } function _pull(address from, uint amt) internal { _move(from, address(this), amt); } } contract BToken is BTokenBase, IERC20 { string private _name = "Cream Pool Token"; string private _symbol = "CRPT"; uint8 private _decimals = 18; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } function allowance(address src, address dst) external view returns (uint) { return _allowance[src][dst]; } function balanceOf(address whom) external view returns (uint) { return _balance[whom]; } function totalSupply() public view returns (uint) { return _totalSupply; } function approve(address dst, uint amt) external returns (bool) { _allowance[msg.sender][dst] = amt; emit Approval(msg.sender, dst, amt); return true; } function increaseApproval(address dst, uint amt) external returns (bool) { _allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt); emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function decreaseApproval(address dst, uint amt) external returns (bool) { uint oldValue = _allowance[msg.sender][dst]; if (amt > oldValue) { _allowance[msg.sender][dst] = 0; } else { _allowance[msg.sender][dst] = bsub(oldValue, amt); } emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function transfer(address dst, uint amt) external returns (bool) { _move(msg.sender, dst, amt); return true; } function transferFrom(address src, address dst, uint amt) external returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender]); _move(src, dst, amt); if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) { _allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt); emit Approval(msg.sender, dst, _allowance[src][msg.sender]); } return true; } } contract BMath is BBronze, BConst, BNum { /********************************************************************************************** // calcSpotPrice // // sP = spotPrice // // bI = tokenBalanceIn ( bI / wI ) 1 // // bO = tokenBalanceOut sP = ----------- * ---------- // // wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcSpotPrice( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint swapFee ) public pure returns (uint spotPrice) { uint numer = bdiv(tokenBalanceIn, tokenWeightIn); uint denom = bdiv(tokenBalanceOut, tokenWeightOut); uint ratio = bdiv(numer, denom); uint scale = bdiv(BONE, bsub(BONE, swapFee)); return (spotPrice = bmul(ratio, scale)); } /********************************************************************************************** // calcOutGivenIn // // aO = tokenAmountOut // // bO = tokenBalanceOut // // bI = tokenBalanceIn / / bI \ (wI / wO) \ // // aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | // // wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / // // wO = tokenWeightOut // // sF = swapFee // **********************************************************************************************/ function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BONE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BONE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); return tokenAmountOut; } /********************************************************************************************** // calcInGivenOut // // aI = tokenAmountIn // // bO = tokenBalanceOut / / bO \ (wO / wI) \ // // bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | // // aO = tokenAmountOut aI = \ \ ( bO - aO ) / / // // wI = tokenWeightIn -------------------------------------------- // // wO = tokenWeightOut ( 1 - sF ) // // sF = swapFee // **********************************************************************************************/ function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BONE); tokenAmountIn = bsub(BONE, swapFee); tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn); return tokenAmountIn; } /********************************************************************************************** // calcPoolOutGivenSingleIn // // pAo = poolAmountOut / \ // // tAi = tokenAmountIn /// / // wI \ \\ \ wI \ // // wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ // // tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS // // tBi = tokenBalanceIn \\ ------------------------------------- / / // // pS = poolSupply \\ tBi / / // // sF = swapFee \ / // **********************************************************************************************/ function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee, uint reservesRatio ) public pure returns (uint poolAmountOut, uint reserves) { // Charge the trading fee for the proportion of tokenAi /// which is implicitly traded to the other pool tokens. // That proportion is (1- weightTokenIn) // tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee); uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); // Exact fee portion of `tokenAmountIn`, i.e. (1- Wt) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz)); reserves = calcReserves(tokenAmountIn, tokenAmountInAfterFee, reservesRatio); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); // uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply; uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return (poolAmountOut, reserves); } /********************************************************************************************** // calcSingleInGivenPoolOut // // tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ // // pS = poolSupply || --------- | ^ | --------- || * bI - bI // // pAo = poolAmountOut \\ pS / \(wI / tW)// // // bI = balanceIn tAi = -------------------------------------------- // // wI = weightIn / wI \ // // tW = totalWeight | 1 - ---- | * sF // // sF = swapFee \ tW / // **********************************************************************************************/ function calcSingleInGivenPoolOut( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint poolAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint newPoolSupply = badd(poolSupply, poolAmountOut); uint poolRatio = bdiv(newPoolSupply, poolSupply); //uint newBalTi = poolRatio^(1/weightTi) * balTi; uint boo = bdiv(BONE, normalizedWeight); uint tokenInRatio = bpow(poolRatio, boo); uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn); uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn); // Do reverse order of fees charged in joinswap_ExternAmountIn, this way // ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ``` //uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ; uint zar = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar)); return tokenAmountIn; } /********************************************************************************************** // calcSingleOutGivenPoolIn // // tAo = tokenAmountOut / / \\ // // bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ // // pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || // // ps = poolSupply \ \\ pS / \(wO / tW)/ // // // wI = tokenWeightIn tAo = \ \ // // // tW = totalWeight / / wO \ \ // // sF = swapFee * | 1 - | 1 - ---- | * sF | // // eF = exitFee \ \ tW / / // **********************************************************************************************/ function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); // charge exit fee on the pool token side // pAiAfterExitFee = pAi*(1-exitFee) uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE)); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); // newBalTo = poolRatio^(1/weightTo) * balTo; uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); // charge swap fee on the output token side //uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee) uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz)); return tokenAmountOut; } /********************************************************************************************** // calcPoolInGivenSingleOut // // pAi = poolAmountIn // / tAo \\ / wO \ \ // // bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ // // tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | // // ps = poolSupply \\ -----------------------------------/ / // // wO = tokenWeightOut pAi = \\ bO / / // // tW = totalWeight ------------------------------------------------------------- // // sF = swapFee ( 1 - eF ) // // eF = exitFee // **********************************************************************************************/ function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee, uint reservesRatio ) public pure returns (uint poolAmountIn, uint reserves) { // charge swap fee on the output token side uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint zar = bmul(bsub(BONE, normalizedWeight), swapFee); uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar)); reserves = calcReserves(tokenAmountOutBeforeSwapFee, tokenAmountOut, reservesRatio); uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); //uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply; uint poolRatio = bpow(tokenOutRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); // charge exit fee on the pool token side // pAi = pAiAfterExitFee/(1-exitFee) poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE)); return (poolAmountIn, reserves); } // `swapFeeAndReserves = amountWithFee - amountWithoutFee` is the swap fee in balancer. // We divide `swapFeeAndReserves` into halves, `actualSwapFee` and `reserves`. // `reserves` goes to the admin and `actualSwapFee` still goes to the liquidity // providers. function calcReserves(uint amountWithFee, uint amountWithoutFee, uint reservesRatio) internal pure returns (uint reserves) { require(amountWithFee >= amountWithoutFee); require(reservesRatio <= BONE); uint swapFeeAndReserves = bsub(amountWithFee, amountWithoutFee); reserves = bmul(swapFeeAndReserves, reservesRatio); require(swapFeeAndReserves >= reserves); } } contract BPool is BBronze, BToken, BMath { struct Record { bool bound; // is token bound to pool uint index; // private uint denorm; // denormalized weight uint balance; } event LOG_SWAP( address indexed caller, address indexed tokenIn, address indexed tokenOut, uint256 tokenAmountIn, uint256 tokenAmountOut ); event LOG_JOIN( address indexed caller, address indexed tokenIn, uint256 tokenAmountIn ); event LOG_EXIT( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); event LOG_DRAIN_RESERVES( address indexed caller, address indexed tokenOut, uint256 tokenAmountOut ); event LOG_CALL( bytes4 indexed sig, address indexed caller, bytes data ) anonymous; modifier _logs_() { emit LOG_CALL(msg.sig, msg.sender, msg.data); _; } modifier _lock_() { require(!_mutex); _mutex = true; _; _mutex = false; } modifier _viewlock_() { require(!_mutex); _; } bool private _mutex; address private _factory; // BFactory address to push token exitFee to address private _controller; // has CONTROL role bool private _publicSwap; // true if PUBLIC can call SWAP functions // `setSwapFee` and `finalize` require CONTROL // `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN` uint private _swapFee; uint private _reservesRatio; bool private _finalized; address[] private _tokens; mapping(address=>Record) private _records; mapping(address=>uint) public totalReserves; uint private _totalWeight; constructor() public { _controller = msg.sender; _factory = msg.sender; _swapFee = MIN_FEE; _reservesRatio = DEFAULT_RESERVES_RATIO; _publicSwap = false; _finalized = false; } function isPublicSwap() external view returns (bool) { return _publicSwap; } function isFinalized() external view returns (bool) { return _finalized; } function isBound(address t) external view returns (bool) { return _records[t].bound; } function getNumTokens() external view returns (uint) { return _tokens.length; } function getCurrentTokens() external view _viewlock_ returns (address[] memory tokens) { return _tokens; } function getFinalTokens() external view _viewlock_ returns (address[] memory tokens) { require(_finalized); return _tokens; } function getDenormalizedWeight(address token) external view _viewlock_ returns (uint) { require(_records[token].bound); return _records[token].denorm; } function getTotalDenormalizedWeight() external view _viewlock_ returns (uint) { return _totalWeight; } function getNormalizedWeight(address token) external view _viewlock_ returns (uint) { require(_records[token].bound); uint denorm = _records[token].denorm; return bdiv(denorm, _totalWeight); } function getBalance(address token) external view _viewlock_ returns (uint) { require(_records[token].bound); return _records[token].balance; } function getSwapFee() external view _viewlock_ returns (uint) { return _swapFee; } function getReservesRatio() external view _viewlock_ returns (uint) { return _reservesRatio; } function getController() external view _viewlock_ returns (address) { return _controller; } function setSwapFee(uint swapFee) external _logs_ _lock_ { require(!_finalized); require(msg.sender == _controller); require(swapFee >= MIN_FEE); require(swapFee <= MAX_FEE); _swapFee = swapFee; } function setReservesRatio(uint reservesRatio) external _logs_ _lock_ { require(!_finalized); require(msg.sender == _controller); require(reservesRatio <= BONE); _reservesRatio = reservesRatio; } function setController(address manager) external _logs_ _lock_ { require(msg.sender == _controller); _controller = manager; } function setPublicSwap(bool public_) external _logs_ _lock_ { require(!_finalized); require(msg.sender == _controller); _publicSwap = public_; } function finalize() external _logs_ _lock_ { require(msg.sender == _controller); require(!_finalized); require(_tokens.length >= MIN_BOUND_TOKENS); _finalized = true; _publicSwap = true; _mintPoolShare(INIT_POOL_SUPPLY); _pushPoolShare(msg.sender, INIT_POOL_SUPPLY); } function bind(address token, uint balance, uint denorm) external _logs_ // _lock_ Bind does not lock because it jumps to `rebind`, which does { require(msg.sender == _controller); require(!_records[token].bound); require(!_finalized); require(_tokens.length < MAX_BOUND_TOKENS); _records[token] = Record({ bound: true, index: _tokens.length, denorm: 0, // balance and denorm will be validated balance: 0 // and set by `rebind` }); _tokens.push(token); rebind(token, balance, denorm); } function rebind(address token, uint balance, uint denorm) public _logs_ _lock_ { require(msg.sender == _controller); require(_records[token].bound); require(!_finalized); require(denorm >= MIN_WEIGHT); require(denorm <= MAX_WEIGHT); require(balance >= MIN_BALANCE); // Adjust the denorm and totalWeight uint oldWeight = _records[token].denorm; if (denorm > oldWeight) { _totalWeight = badd(_totalWeight, bsub(denorm, oldWeight)); require(_totalWeight <= MAX_TOTAL_WEIGHT); } else if (denorm < oldWeight) { _totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm)); } _records[token].denorm = denorm; // Adjust the balance record and actual token balance uint oldBalance = _records[token].balance; _records[token].balance = balance; if (balance > oldBalance) { _pullUnderlying(token, msg.sender, bsub(balance, oldBalance)); } else if (balance < oldBalance) { // In this case liquidity is being withdrawn, so charge EXIT_FEE uint tokenBalanceWithdrawn = bsub(oldBalance, balance); uint tokenExitFee = bmul(tokenBalanceWithdrawn, EXIT_FEE); _pushUnderlying(token, msg.sender, bsub(tokenBalanceWithdrawn, tokenExitFee)); _pushUnderlying(token, _factory, tokenExitFee); } } function unbind(address token) external _logs_ _lock_ { require(msg.sender == _controller); require(_records[token].bound); require(!_finalized); uint tokenBalance = _records[token].balance; uint tokenExitFee = bmul(tokenBalance, EXIT_FEE); _totalWeight = bsub(_totalWeight, _records[token].denorm); // Swap the token-to-unbind with the last token, // then delete the last token uint index = _records[token].index; uint last = _tokens.length - 1; _tokens[index] = _tokens[last]; _records[_tokens[index]].index = index; _tokens.pop(); _records[token] = Record({ bound: false, index: 0, denorm: 0, balance: 0 }); _pushUnderlying(token, msg.sender, bsub(tokenBalance, tokenExitFee)); _pushUnderlying(token, _factory, tokenExitFee); } // Absorb any tokens that have been sent to this contract into the pool function gulp(address token) external _logs_ _lock_ { require(_records[token].bound); _records[token].balance = IERC20(token).balanceOf(address(this)); } function seize(address token, uint amount) external _logs_ _lock_ { require(msg.sender == _controller); require(!_records[token].bound); uint bal = IERC20(token).balanceOf(address(this)); require(amount <= bal); _pushUnderlying(token, msg.sender, amount); } function getSpotPrice(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { require(_records[tokenIn].bound); require(_records[tokenOut].bound); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee); } function getSpotPriceSansFee(address tokenIn, address tokenOut) external view _viewlock_ returns (uint spotPrice) { require(_records[tokenIn].bound); require(_records[tokenOut].bound); Record storage inRecord = _records[tokenIn]; Record storage outRecord = _records[tokenOut]; return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, 0); } function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external _logs_ _lock_ { require(_finalized); uint poolTotal = totalSupply(); uint ratio = bdiv(poolAmountOut, poolTotal); require(ratio != 0); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountIn = bmul(ratio, bal); require(tokenAmountIn != 0); require(tokenAmountIn <= maxAmountsIn[i]); _records[t].balance = badd(_records[t].balance, tokenAmountIn); emit LOG_JOIN(msg.sender, t, tokenAmountIn); _pullUnderlying(t, msg.sender, tokenAmountIn); } _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); } function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external _logs_ _lock_ { require(_finalized); uint poolTotal = totalSupply(); uint exitFee = bmul(poolAmountIn, EXIT_FEE); uint pAiAfterExitFee = bsub(poolAmountIn, exitFee); uint ratio = bdiv(pAiAfterExitFee, poolTotal); require(ratio != 0); _pullPoolShare(msg.sender, poolAmountIn); _pushPoolShare(_factory, exitFee); _burnPoolShare(pAiAfterExitFee); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint bal = _records[t].balance; uint tokenAmountOut = bmul(ratio, bal); require(tokenAmountOut != 0); require(tokenAmountOut >= minAmountsOut[i]); _records[t].balance = bsub(_records[t].balance, tokenAmountOut); emit LOG_EXIT(msg.sender, t, tokenAmountOut); _pushUnderlying(t, msg.sender, tokenAmountOut); } } function swapExactAmountIn( address tokenIn, uint tokenAmountIn, address tokenOut, uint minAmountOut, uint maxPrice ) external _logs_ _lock_ returns (uint tokenAmountOut, uint spotPriceAfter) { require(_records[tokenIn].bound); require(_records[tokenOut].bound); require(_publicSwap); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO)); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice); tokenAmountOut = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut); uint tokenAmountOutZeroFee = calcOutGivenIn( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountIn, 0 ); uint reserves = calcReserves( tokenAmountOutZeroFee, tokenAmountOut, _reservesRatio ); inRecord.balance = badd(inRecord.balance, tokenAmountIn); // Subtract `reserves`. outRecord.balance = bsub(bsub(outRecord.balance, tokenAmountOut), reserves); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore); require(spotPriceAfter <= maxPrice); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut)); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountOut, spotPriceAfter); } function swapExactAmountOut( address tokenIn, uint maxAmountIn, address tokenOut, uint tokenAmountOut, uint maxPrice ) external _logs_ _lock_ returns (uint tokenAmountIn, uint spotPriceAfter) { require(_records[tokenIn].bound); require(_records[tokenOut].bound); require(_publicSwap); Record storage inRecord = _records[address(tokenIn)]; Record storage outRecord = _records[address(tokenOut)]; require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO)); uint spotPriceBefore = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceBefore <= maxPrice); tokenAmountIn = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, _swapFee ); require(tokenAmountIn <= maxAmountIn); uint tokenAmountInZeroFee = calcInGivenOut( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, tokenAmountOut, 0 ); uint reserves = calcReserves( tokenAmountIn, tokenAmountInZeroFee, _reservesRatio ); // Subtract `reserves` which is reserved for admin. inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves); outRecord.balance = bsub(outRecord.balance, tokenAmountOut); spotPriceAfter = calcSpotPrice( inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee ); require(spotPriceAfter >= spotPriceBefore); require(spotPriceAfter <= maxPrice); require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut)); emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return (tokenAmountIn, spotPriceAfter); } function joinswapExternAmountIn(address tokenIn, uint tokenAmountIn, uint minPoolAmountOut) external _logs_ _lock_ returns (uint poolAmountOut) { require(_finalized); require(_records[tokenIn].bound); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO)); Record storage inRecord = _records[tokenIn]; uint reserves; (poolAmountOut, reserves) = calcPoolOutGivenSingleIn( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, tokenAmountIn, _swapFee, _reservesRatio ); require(poolAmountOut >= minPoolAmountOut); inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return poolAmountOut; } function joinswapPoolAmountOut(address tokenIn, uint poolAmountOut, uint maxAmountIn) external _logs_ _lock_ returns (uint tokenAmountIn) { require(_finalized); require(_records[tokenIn].bound); Record storage inRecord = _records[tokenIn]; tokenAmountIn = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, _swapFee ); require(tokenAmountIn != 0); require(tokenAmountIn <= maxAmountIn); require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO)); uint tokenAmountInZeroFee = calcSingleInGivenPoolOut( inRecord.balance, inRecord.denorm, _totalSupply, _totalWeight, poolAmountOut, 0 ); uint reserves = calcReserves( tokenAmountIn, tokenAmountInZeroFee, _reservesRatio ); inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves); emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn); totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves); _mintPoolShare(poolAmountOut); _pushPoolShare(msg.sender, poolAmountOut); _pullUnderlying(tokenIn, msg.sender, tokenAmountIn); return tokenAmountIn; } function exitswapPoolAmountIn(address tokenOut, uint poolAmountIn, uint minAmountOut) external _logs_ _lock_ returns (uint tokenAmountOut) { require(_finalized); require(_records[tokenOut].bound); Record storage outRecord = _records[tokenOut]; tokenAmountOut = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, _swapFee ); require(tokenAmountOut >= minAmountOut); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO)); uint tokenAmountOutZeroFee = calcSingleOutGivenPoolIn( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, poolAmountIn, 0 ); uint reserves = calcReserves( tokenAmountOutZeroFee, tokenAmountOut, _reservesRatio ); outRecord.balance = bsub(bsub(outRecord.balance, tokenAmountOut), reserves); uint exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_factory, exitFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return tokenAmountOut; } function exitswapExternAmountOut(address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn) external _logs_ _lock_ returns (uint poolAmountIn) { require(_finalized); require(_records[tokenOut].bound); require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO)); Record storage outRecord = _records[tokenOut]; uint reserves; (poolAmountIn, reserves) = calcPoolInGivenSingleOut( outRecord.balance, outRecord.denorm, _totalSupply, _totalWeight, tokenAmountOut, _swapFee, _reservesRatio ); require(poolAmountIn != 0); require(poolAmountIn <= maxPoolAmountIn); outRecord.balance = bsub(bsub(outRecord.balance, tokenAmountOut), reserves); uint exitFee = bmul(poolAmountIn, EXIT_FEE); emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut); totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves); _pullPoolShare(msg.sender, poolAmountIn); _burnPoolShare(bsub(poolAmountIn, exitFee)); _pushPoolShare(_factory, exitFee); _pushUnderlying(tokenOut, msg.sender, tokenAmountOut); return poolAmountIn; } function drainTotalReserves(address reservesAddress) external _logs_ _lock_ { require(msg.sender == _factory); for (uint i = 0; i < _tokens.length; i++) { address t = _tokens[i]; uint tokenAmountOut = totalReserves[t]; totalReserves[t] = 0; emit LOG_DRAIN_RESERVES(reservesAddress, t, tokenAmountOut); _pushUnderlying(t, reservesAddress, tokenAmountOut); } } // == // 'Underlying' token-manipulation functions make external calls but are NOT locked // You must `_lock_` or otherwise ensure reentry-safety function _pullUnderlying(address erc20, address from, uint amount) internal { bool xfer = IERC20(erc20).transferFrom(from, address(this), amount); require(xfer); } function _pushUnderlying(address erc20, address to, uint amount) internal { bool xfer = IERC20(erc20).transfer(to, amount); require(xfer); } function _pullPoolShare(address from, uint amount) internal { _pull(from, amount); } function _pushPoolShare(address to, uint amount) internal { _push(to, amount); } function _mintPoolShare(uint amount) internal { _mint(amount); } function _burnPoolShare(uint amount) internal { _burn(amount); } }
0x608060405234801561001057600080fd5b506004361061039d5760003560e01c806392eefe9b116101eb578063bc694ea211610110578063dd62ed3e116100a8578063dd62ed3e14610c51578063e4a28a52146104fd578063e4e1e53814610c7f578063eb9253c014610cb1578063ec09302114610cdd578063f1b8a9b714610ce5578063f8b2cb4f14610d0b578063f8d6aed414610d31578063fde924f714610d6c5761039d565b8063bc694ea214610b7f578063be3bbd2e14610b87578063c36596a614610571578063c6580d1214610bdf578063cc77828d14610be7578063cd2ed8fb14610bef578063cf5e7bd314610bf7578063d4cadf6814610c1d578063d73dd62314610c255761039d565b8063a9059cbb11610183578063a9059cbb14610a40578063aeeead6614610a6c578063b02f0b7314610a92578063b0e0d13614610b07578063b4a8e10114610b0f578063b7b800a414610b2c578063ba019dab14610b34578063ba9530a614610b3c578063bc063e1a14610b775761039d565b806392eefe9b1461098f578063936c3477146109b55780639381cd2b146109bd57806393c88d14146109c5578063948d8ce6146109cd57806395d89b41146109f3578063992e2a92146109fb5780639a86139b14610a03578063a221ee4914610a0b5761039d565b806346ab38f1116102d15780636d0800bc116102695780636d0800bc1461084a57806370a082311461087057806376c7a3c7146108965780637c5e9ea41461089e5780638201aa3f146108de578063867378c51461091e57806389298012146109265780638c28cbe8146109615780638d4e4083146109875761039d565b806346ab38f1146106a957806349b59552146106db5780634bb278f3146106fa5780634d2fd81d146107025780634f69c0d41461070a5780635c1bbaf71461077f5780635db34277146107ba57806366188463146107ec5780636d06dfa0146108185761039d565b8063189d00ca11610344578063189d00ca14610569578063218b53821461057157806321abba011461057957806323b872dd146105ba5780632f37b624146105f05780633018205f14610616578063313ce5671461063a57806334e19907146106585780633fdddaa2146106775761039d565b8063024eb2e3146103a257806302c96748146103fc57806306fdde0314610440578063095ea7b3146104bd57806309a3bbe4146104fd5780631446a7ff1461050557806315e84af91461053357806318160ddd14610561575b600080fd5b6103e3600480360360e08110156103b857600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c00135610d74565b6040805192835260208301919091528051918290030190f35b61042e6004803603606081101561041257600080fd5b506001600160a01b038135169060208101359060400135610e43565b60408051918252519081900360200190f35b610448611093565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561048257818101518382015260200161046a565b50505050905090810190601f1680156104af5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6104e9600480360360408110156104d357600080fd5b506001600160a01b038135169060200135611129565b604080519115158252519081900360200190f35b61042e61117e565b61042e6004803603604081101561051b57600080fd5b506001600160a01b038135811691602001351661118b565b61042e6004803603604081101561054957600080fd5b506001600160a01b038135811691602001351661123a565b61042e6112e0565b61042e6112e6565b61042e6112fa565b6103e3600480360360e081101561058f57600080fd5b5080359060208101359060408101359060608101359060808101359060a08101359060c00135611306565b6104e9600480360360608110156105d057600080fd5b506001600160a01b038135811691602081013590911690604001356113b3565b6104e96004803603602081101561060657600080fd5b50356001600160a01b03166114cd565b61061e6114eb565b604080516001600160a01b039092168252519081900360200190f35b610642611513565b6040805160ff9092168252519081900360200190f35b6106756004803603602081101561066e57600080fd5b503561151c565b005b6106756004803603606081101561068d57600080fd5b506001600160a01b0381351690602081013590604001356115ff565b61042e600480360360608110156106bf57600080fd5b506001600160a01b03813516906020810135906040013561183b565b610675600480360360208110156106f157600080fd5b50351515611a8f565b610675611b64565b61042e611c74565b6106756004803603604081101561072057600080fd5b81359190810190604081016020820135600160201b81111561074157600080fd5b82018360208201111561075357600080fd5b803590602001918460208302840111600160201b8311171561077457600080fd5b509092509050611c93565b61042e600480360360c081101561079557600080fd5b5080359060208101359060408101359060608101359060808101359060a00135611e5d565b61042e600480360360608110156107d057600080fd5b506001600160a01b038135169060208101359060400135611f10565b6104e96004803603604081101561080257600080fd5b506001600160a01b038135169060200135612117565b61042e6004803603606081101561082e57600080fd5b506001600160a01b0381351690602081013590604001356121ef565b61042e6004803603602081101561086057600080fd5b50356001600160a01b0316612407565b61042e6004803603602081101561088657600080fd5b50356001600160a01b0316612419565b61042e612434565b6103e3600480360360a08110156108b457600080fd5b506001600160a01b0381358116916020810135916040820135169060608101359060800135612446565b6103e3600480360360a08110156108f457600080fd5b506001600160a01b038135811691602081013591604082013516906060810135906080013561273b565b61042e612a15565b61042e600480360360c081101561093c57600080fd5b5080359060208101359060408101359060608101359060808101359060a00135612a29565b6106756004803603602081101561097757600080fd5b50356001600160a01b0316612ad9565b6104e9612c1f565b610675600480360360208110156109a557600080fd5b50356001600160a01b0316612c28565b61042e612cf3565b61042e612d12565b61042e612d1f565b61042e600480360360208110156109e357600080fd5b50356001600160a01b0316612d2f565b610448612d8b565b61042e612dec565b61042e612df8565b61042e600480360360a0811015610a2157600080fd5b5080359060208101359060408101359060608101359060800135612e05565b6104e960048036036040811015610a5657600080fd5b506001600160a01b038135169060200135612e6a565b61067560048036036020811015610a8257600080fd5b50356001600160a01b0316612e80565b61067560048036036040811015610aa857600080fd5b81359190810190604081016020820135600160201b811115610ac957600080fd5b820183602082011115610adb57600080fd5b803590602001918460208302840111600160201b83111715610afc57600080fd5b509092509050612fc6565b61042e6131dd565b61067560048036036020811015610b2557600080fd5b50356131e2565b61042e6132b3565b61042e6132b8565b61042e600480360360c0811015610b5257600080fd5b5080359060208101359060408101359060608101359060808101359060a001356132bd565b61042e61333e565b61042e61334e565b610b8f61335a565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610bcb578181015183820152602001610bb3565b505050509050019250505060405180910390f35b61042e6133e0565b610b8f6133e5565b61042e6133fd565b61067560048036036020811015610c0d57600080fd5b50356001600160a01b0316613403565b61042e61369f565b6104e960048036036040811015610c3b57600080fd5b506001600160a01b0381351690602001356136be565b61042e60048036036040811015610c6757600080fd5b506001600160a01b038135811691602001351661373f565b61067560048036036060811015610c9557600080fd5b506001600160a01b03813516906020810135906040013561376a565b61067560048036036040811015610cc757600080fd5b506001600160a01b0381351690602001356138d9565b61042e613a3d565b61042e60048036036020811015610cfb57600080fd5b50356001600160a01b0316613a4d565b61042e60048036036020811015610d2157600080fd5b50356001600160a01b0316613abb565b61042e600480360360c0811015610d4757600080fd5b5080359060208101359060408101359060608101359060808101359060a00135613b17565b6104e9613b9a565b6000806000610d838988613baa565b90506000610da2610d9c670de0b6b3a764000084613c10565b87613c36565b90506000610dc188610dbc670de0b6b3a764000085613c10565b613baa565b9050610dce818988613c82565b93506000610ddc8d83613c10565b90506000610dea828f613baa565b90506000610df88287613ccd565b90506000610e06828f613c36565b90506000610e148f83613c10565b9050610e2d81610dbc670de0b6b3a76400006000613c10565b9950505050505050505097509795505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615610ebb57600080fd5b6005805461ff00191661010017905560095460ff16610ed957600080fd5b6001600160a01b0384166000908152600b602052604090205460ff16610efe57600080fd5b6001600160a01b0384166000908152600b60205260409020600390810154610f3391670de0b6b3a76400005b04600101613c36565b831115610f3f57600080fd5b6000600b6000866001600160a01b03166001600160a01b0316815260200190815260200160002090506000610f8982600301548360020154600254600d5489600754600854610d74565b909350905082610f9857600080fd5b83831115610fa557600080fd5b610fbc610fb6836003015487613c10565b82613c10565b60038301556000610fcd8482613c36565b6040805188815290519192506001600160a01b0389169133916000805160206141fe833981519152919081900360200190a36001600160a01b0387166000908152600c60205260409020546110229083613d5a565b6001600160a01b0388166000908152600c60205260409020556110453385613d6c565b6110576110528583613c10565b613d7a565b600554611073906201000090046001600160a01b031682613d86565b61107e873388613d90565b5050506005805461ff00191690559392505050565b60038054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526060939092909183018282801561111f5780601f106110f45761010080835404028352916020019161111f565b820191906000526020600020905b81548152906001019060200180831161110257829003601f168201915b5050505050905090565b3360008181526001602090815260408083206001600160a01b0387168085529083528184208690558151868152915193949093909260008051602061421e833981519152928290030190a35060015b92915050565b6802b5e3af16b188000081565b600554600090610100900460ff16156111a357600080fd5b6001600160a01b0383166000908152600b602052604090205460ff166111c857600080fd5b6001600160a01b0382166000908152600b602052604090205460ff166111ed57600080fd5b6001600160a01b038084166000908152600b602052604080822092851682528120600380840154600280860154928401549084015493946112319492939290612e05565b95945050505050565b600554600090610100900460ff161561125257600080fd5b6001600160a01b0383166000908152600b602052604090205460ff1661127757600080fd5b6001600160a01b0382166000908152600b602052604090205460ff1661129c57600080fd5b6001600160a01b038084166000908152600b602052604080822092851682529020600380830154600280850154928401549084015460075461123194929190612e05565b60025490565b6402540be400670de0b6b3a76400005b0481565b670de0b6b3a764000081565b60008060006113158988613baa565b9050600061132e610d9c670de0b6b3a764000084613c10565b9050600061134d88611348670de0b6b3a764000085613c10565b613c36565b905061135a888288613c82565b935060006113688d83613d5a565b90506000611376828f613baa565b905060006113848287613ccd565b90506000611392828f613c36565b905061139e818f613c10565b98505050505050505097509795505050505050565b6000336001600160a01b03851614806113ef57506001600160a01b03841660009081526001602090815260408083203384529091529020548211155b6113f857600080fd5b611403848484613e21565b336001600160a01b0385161480159061144157506001600160a01b038416600090815260016020908152604080832033845290915290205460001914155b156114c3576001600160a01b03841660009081526001602090815260408083203384529091529020546114749083613c10565b6001600160a01b038581166000908152600160209081526040808320338085529083529281902085905580519485525192871693919260008051602061421e8339815191529281900390910190a35b5060019392505050565b6001600160a01b03166000908152600b602052604090205460ff1690565b600554600090610100900460ff161561150357600080fd5b506006546001600160a01b031690565b60055460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561159257600080fd5b6005805461ff00191661010017905560095460ff16156115b157600080fd5b6006546001600160a01b031633146115c857600080fd5b64e8d4a510008110156115da57600080fd5b67016345785d8a00008111156115ef57600080fd5b6007556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561167557600080fd5b6005805461ff001916610100179055600654336001600160a01b039091161461169d57600080fd5b6001600160a01b0383166000908152600b602052604090205460ff166116c257600080fd5b60095460ff16156116d257600080fd5b670de0b6b3a76400008110156116e757600080fd5b6802b5e3af16b18800008111156116fd57600080fd5b620f424082101561170d57600080fd5b6001600160a01b0383166000908152600b60205260409020600201548082111561176557611746600d546117418484613c10565b613d5a565b600d8190556802b5e3af16b1880000101561176057600080fd5b611786565b8082101561178657611782600d5461177d8385613c10565b613c10565b600d555b6001600160a01b0384166000908152600b6020526040902060028101839055600301805490849055808411156117cf576117ca85336117c58785613c10565b613ee0565b611829565b808410156118295760006117e38286613c10565b905060006117f2826000613c36565b905061180887336118038585613c10565b613d90565b6005546118269088906201000090046001600160a01b031683613d90565b50505b50506005805461ff0019169055505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156118b357600080fd5b6005805461ff00191661010017905560095460ff166118d157600080fd5b6001600160a01b0384166000908152600b602052604090205460ff166118f657600080fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d5460075461193094939291908990612a29565b91508282101561193f57600080fd5b6001600160a01b0385166000908152600b6020526040902060039081015461196f91670de0b6b3a7640000610f2a565b82111561197b57600080fd5b600061199882600301548360020154600254600d54896000612a29565b905060006119a98285600854613c82565b90506119bc610fb6846003015486613c10565b600384015560006119cd8782613c36565b6040805187815290519192506001600160a01b038a169133916000805160206141fe833981519152919081900360200190a36001600160a01b0388166000908152600c6020526040902054611a229083613d5a565b6001600160a01b0389166000908152600c6020526040902055611a453388613d6c565b611a526110528883613c10565b600554611a6e906201000090046001600160a01b031682613d86565b611a79883387613d90565b505050506005805461ff00191690559392505050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611b0557600080fd5b6005805461ff00191661010017905560095460ff1615611b2457600080fd5b6006546001600160a01b03163314611b3b57600080fd5b60068054911515600160a01b0260ff60a01b199092169190911790556005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611bda57600080fd5b6005805461ff001916610100179055600654336001600160a01b0390911614611c0257600080fd5b60095460ff1615611c1257600080fd5b600a5460021115611c2257600080fd5b6009805460ff191660011790556006805460ff60a01b1916600160a01b179055611c5468056bc75e2d63100000613f39565b611c673368056bc75e2d63100000613d86565b6005805461ff0019169055565b600554600090610100900460ff1615611c8c57600080fd5b5060085490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611d0957600080fd5b6005805461ff00191661010017905560095460ff16611d2757600080fd5b6000611d316112e0565b90506000611d3f8583613baa565b905080611d4b57600080fd5b60005b600a54811015611e49576000600a8281548110611d6757fe5b60009182526020808320909101546001600160a01b0316808352600b909152604082206003015490925090611d9c8583613c36565b905080611da857600080fd5b878785818110611db457fe5b90506020020135811115611dc757600080fd5b6001600160a01b0383166000908152600b6020526040902060030154611ded9082613d5a565b6001600160a01b0384166000818152600b60209081526040918290206003019390935580518481529051919233926000805160206141be8339815191529281900390910190a3611e3e833383613ee0565b505050600101611d4e565b50611e5385613f39565b6118293386613d86565b600080611e6a8786613baa565b90506000611e788786613d5a565b90506000611e868289613baa565b90506000611e9c670de0b6b3a764000085613baa565b90506000611eaa8383613ccd565b90506000611eb8828e613c36565b90506000611ec6828f613c10565b90506000611ee5611edf670de0b6b3a76400008a613c10565b8b613c36565b9050611efd82610dbc670de0b6b3a764000084613c10565b9f9e505050505050505050505050505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615611f8857600080fd5b6005805461ff00191661010017905560095460ff16611fa657600080fd5b6001600160a01b0384166000908152600b602052604090205460ff16611fcb57600080fd5b6001600160a01b0384166000908152600b6020526040902060030154611ffd906002670de0b6b3a76400005b04613c36565b83111561200957600080fd5b6000600b6000866001600160a01b03166001600160a01b031681526020019081526020016000209050600061205382600301548360020154600254600d5489600754600854611306565b90935090508383101561206557600080fd5b612076610fb6836003015487613d5a565b60038301556040805186815290516001600160a01b0388169133916000805160206141be8339815191529181900360200190a36001600160a01b0386166000908152600c60205260409020546120cc9082613d5a565b6001600160a01b0387166000908152600c60205260409020556120ee83613f39565b6120f83384613d86565b612103863387613ee0565b50506005805461ff00191690559392505050565b3360009081526001602090815260408083206001600160a01b03861684529091528120548083111561216c573360009081526001602090815260408083206001600160a01b038816845290915281205561219b565b6121768184613c10565b3360009081526001602090815260408083206001600160a01b03891684529091529020555b3360008181526001602090815260408083206001600160a01b03891680855290835292819020548151908152905192939260008051602061421e833981519152929181900390910190a35060019392505050565b6000336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561226757600080fd5b6005805461ff00191661010017905560095460ff1661228557600080fd5b6001600160a01b0384166000908152600b602052604090205460ff166122aa57600080fd5b6001600160a01b0384166000908152600b6020526040902060038101546002808301549054600d546007546122e494939291908990611e5d565b9150816122f057600080fd5b828211156122fd57600080fd5b6001600160a01b0385166000908152600b602052604090206003015461232d906002670de0b6b3a7640000611ff7565b82111561233957600080fd5b600061235682600301548360020154600254600d54896000611e5d565b905060006123678483600854613c82565b905061237a610fb6846003015486613d5a565b60038401556040805185815290516001600160a01b0389169133916000805160206141be8339815191529181900360200190a36001600160a01b0387166000908152600c60205260409020546123d09082613d5a565b6001600160a01b0388166000908152600c60205260409020556123f286613f39565b6123fc3387613d86565b61107e873386613ee0565b600c6020526000908152604090205481565b6001600160a01b031660009081526020819052604090205490565b620f4240670de0b6b3a76400006112f6565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156124ad57600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff166124e157600080fd5b6001600160a01b0385166000908152600b602052604090205460ff1661250657600080fd5b600654600160a01b900460ff1661251c57600080fd5b6001600160a01b038088166000908152600b60205260408082209288168252902060038082015461255591670de0b6b3a7640000610f2a565b86111561256157600080fd5b60006125828360030154846002015484600301548560020154600754612e05565b90508581111561259157600080fd5b6125b183600301548460020154846003015485600201548b600754613b17565b9450888511156125c057600080fd5b60006125e184600301548560020154856003015486600201548c6000613b17565b905060006125f28783600854613c82565b9050612605610fb6866003015489613d5a565b856003018190555061261b84600301548a613c10565b60038086018290558601546002808801549087015460075461263e949190612e05565b95508286101561264d57600080fd5b8786111561265a57600080fd5b612664878a613baa565b83111561267057600080fd5b896001600160a01b03168c6001600160a01b0316336001600160a01b03167f908fb5ee8f16c6bc9bc3690973819f32a4d4b10188134543c88706e0e1d433788a8d604051808381526020018281526020019250505060405180910390a46001600160a01b038c166000908152600c60205260409020546126f09082613d5a565b6001600160a01b038d166000908152600c60205260409020556127148c3389613ee0565b61271f8a338b613d90565b50505050506005805461ff001916905590969095509350505050565b60408051602080825236908201819052600092839233926001600160e01b03198535169285929081908101848480828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff16156127a257600080fd5b6005805461ff0019166101001790556001600160a01b0387166000908152600b602052604090205460ff166127d657600080fd5b6001600160a01b0385166000908152600b602052604090205460ff166127fb57600080fd5b600654600160a01b900460ff1661281157600080fd5b6001600160a01b038088166000908152600b602052604080822092881682529020600382015461284b906002670de0b6b3a7640000611ff7565b88111561285757600080fd5b60006128788360030154846002015484600301548560020154600754612e05565b90508581111561288757600080fd5b6128a783600301548460020154846003015485600201548d6007546132bd565b9450868510156128b657600080fd5b60006128d784600301548560020154856003015486600201548e60006132bd565b905060006128e88288600854613c82565b90506128f885600301548c613d5a565b8560030181905550612911610fb6856003015489613c10565b600380860182905586015460028088015490870154600754612934949190612e05565b95508286101561294357600080fd5b8786111561295057600080fd5b61295a8b88613baa565b83111561296657600080fd5b896001600160a01b03168c6001600160a01b0316336001600160a01b03167f908fb5ee8f16c6bc9bc3690973819f32a4d4b10188134543c88706e0e1d433788e8b604051808381526020018281526020019250505060405180910390a46001600160a01b038a166000908152600c60205260409020546129e69082613d5a565b6001600160a01b038b166000908152600c6020526040902055612a0a8c338d613ee0565b61271f8a3389613d90565b64e8d4a51000670de0b6b3a76400006112f6565b600080612a368786613baa565b90506000612a5185611348670de0b6b3a76400006000613c10565b90506000612a5f8883613c10565b90506000612a6d828a613baa565b90506000612a8c82612a87670de0b6b3a764000088613baa565b613ccd565b90506000612a9a828e613c36565b90506000612aa88e83613c10565b90506000612ac1611edf670de0b6b3a76400008a613c10565b9050611efd82611348670de0b6b3a764000084613c10565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612b4f57600080fd5b6005805461ff0019166101001790556001600160a01b0381166000908152600b602052604090205460ff16612b8357600080fd5b604080516370a0823160e01b815230600482015290516001600160a01b038316916370a08231916024808301926020929190829003018186803b158015612bc957600080fd5b505afa158015612bdd573d6000803e3d6000fd5b505050506040513d6020811015612bf357600080fd5b50516001600160a01b039091166000908152600b60205260409020600301556005805461ff0019169055565b60095460ff1690565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612c9e57600080fd5b6005805461ff001916610100179055600654336001600160a01b0390911614612cc657600080fd5b600680546001600160a01b0319166001600160a01b03929092169190911790556005805461ff0019169055565b600554600090610100900460ff1615612d0b57600080fd5b50600d5490565b68056bc75e2d6310000081565b6005670de0b6b3a76400006112f6565b600554600090610100900460ff1615612d4757600080fd5b6001600160a01b0382166000908152600b602052604090205460ff16612d6c57600080fd5b506001600160a01b03166000908152600b602052604090206002015490565b60048054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526060939092909183018282801561111f5780601f106110f45761010080835404028352916020019161111f565b6704a03ce68d21555681565b6542524f4e5a4560d01b90565b600080612e128787613baa565b90506000612e208686613baa565b90506000612e2e8383613baa565b90506000612e50670de0b6b3a7640000610dbc670de0b6b3a764000089613c10565b9050612e5c8282613c36565b9a9950505050505050505050565b6000612e77338484613e21565b50600192915050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff1615612ef657600080fd5b6005805461010061ff001990911617908190556201000090046001600160a01b03163314612f2357600080fd5b60005b600a54811015612fb7576000600a8281548110612f3f57fe5b60009182526020808320909101546001600160a01b03908116808452600c835260408085208054959055805185815290519195508593928816927f261074971f6b45f02124a88c43d5c95e174626f867c87684fb60dbbe35ec2cd292918290030190a3612fad828583613d90565b5050600101612f26565b50506005805461ff0019169055565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561303c57600080fd5b6005805461ff00191661010017905560095460ff1661305a57600080fd5b60006130646112e0565b90506000613073856000613c36565b905060006130818683613c10565b9050600061308f8285613baa565b90508061309b57600080fd5b6130a53388613d6c565b6005546130c1906201000090046001600160a01b031684613d86565b6130ca82613d7a565b60005b600a548110156131c8576000600a82815481106130e657fe5b60009182526020808320909101546001600160a01b0316808352600b90915260408220600301549092509061311b8583613c36565b90508061312757600080fd5b89898581811061313357fe5b9050602002013581101561314657600080fd5b6001600160a01b0383166000908152600b602052604090206003015461316c9082613c10565b6001600160a01b0384166000818152600b60209081526040918290206003019390935580518481529051919233926000805160206141fe8339815191529281900390910190a36131bd833383613d90565b5050506001016130cd565b50506005805461ff0019169055505050505050565b600881565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561325857600080fd5b6005805461ff00191661010017905560095460ff161561327757600080fd5b6006546001600160a01b0316331461328e57600080fd5b670de0b6b3a76400008111156132a357600080fd5b6008556005805461ff0019169055565b600281565b600181565b6000806132ca8786613baa565b905060006132e0670de0b6b3a764000085613c10565b90506132ec8582613c36565b905060006132fe8a610dbc8c85613d5a565b9050600061330c8285613ccd565b90506000613322670de0b6b3a764000083613c10565b905061332e8a82613c36565b9c9b505050505050505050505050565b600a670de0b6b3a76400006112f6565b671bc16d674ec7ffff81565b600554606090610100900460ff161561337257600080fd5b60095460ff1661338157600080fd5b600a80548060200260200160405190810160405280929190818152602001828054801561111f57602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116133b9575050505050905090565b600081565b600554606090610100900460ff161561338157600080fd5b600a5490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561347957600080fd5b6005805461ff001916610100179055600654336001600160a01b03909116146134a157600080fd5b6001600160a01b0381166000908152600b602052604090205460ff166134c657600080fd5b60095460ff16156134d657600080fd5b6001600160a01b0381166000908152600b6020526040812060030154906134fd8282613c36565b600d546001600160a01b0385166000908152600b602052604090206002015491925061352891613c10565b600d556001600160a01b0383166000908152600b6020526040902060010154600a8054600019810191908290811061355c57fe5b600091825260209091200154600a80546001600160a01b03909216918490811061358257fe5b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555081600b6000600a85815481106135c257fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902060010155600a8054806135f557fe5b60008281526020808220600019908401810180546001600160a01b031916905590920190925560408051608081018252838152808301848152818301858152606083018681526001600160a01b038c168752600b909552929094209051815460ff1916901515178155925160018401555160028301555160039091015561368185336118038787613c10565b6005546118299086906201000090046001600160a01b031685613d90565b600554600090610100900460ff16156136b757600080fd5b5060075490565b3360009081526001602090815260408083206001600160a01b03861684529091528120546136ec9083613d5a565b3360008181526001602090815260408083206001600160a01b03891680855290835292819020859055805194855251919360008051602061421e833981519152929081900390910190a350600192915050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a26006546001600160a01b031633146137e257600080fd5b6001600160a01b0383166000908152600b602052604090205460ff161561380857600080fd5b60095460ff161561381857600080fd5b600a5460081161382757600080fd5b604080516080810182526001808252600a805460208085019182526000858701818152606087018281526001600160a01b038c16808452600b9094529782209651875460ff1916901515178755925186860155915160028601559451600390940193909355805491820181559091527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a80180546001600160a01b03191690911790556138d48383836115ff565b505050565b336001600160a01b03166000356001600160e01b0319166001600160e01b03191660003660405180806020018281038252848482818152602001925080828437600083820152604051601f909101601f19169092018290039550909350505050a2600554610100900460ff161561394f57600080fd5b6005805461ff001916610100179055600654336001600160a01b039091161461397757600080fd5b6001600160a01b0382166000908152600b602052604090205460ff161561399d57600080fd5b604080516370a0823160e01b815230600482015290516000916001600160a01b038516916370a0823191602480820192602092909190829003018186803b1580156139e757600080fd5b505afa1580156139fb573d6000803e3d6000fd5b505050506040513d6020811015613a1157600080fd5b5051905080821115613a2257600080fd5b613a2d833384613d90565b50506005805461ff001916905550565b6002670de0b6b3a76400006112f6565b600554600090610100900460ff1615613a6557600080fd5b6001600160a01b0382166000908152600b602052604090205460ff16613a8a57600080fd5b6001600160a01b0382166000908152600b6020526040902060020154600d54613ab4908290613baa565b9392505050565b600554600090610100900460ff1615613ad357600080fd5b6001600160a01b0382166000908152600b602052604090205460ff16613af857600080fd5b506001600160a01b03166000908152600b602052604090206003015490565b600080613b248588613baa565b90506000613b328786613c10565b90506000613b408883613baa565b90506000613b4e8285613ccd565b9050613b6281670de0b6b3a7640000613c10565b9050613b76670de0b6b3a764000087613c10565b9450613b8b613b858c83613c36565b86613baa565b9b9a5050505050505050505050565b600654600160a01b900460ff1690565b600081613bb657600080fd5b670de0b6b3a76400008302831580613bde5750670de0b6b3a7640000848281613bdb57fe5b04145b613be757600080fd5b60028304810181811015613bfa57600080fd5b6000848281613c0557fe5b049695505050505050565b6000806000613c1f8585613f42565b915091508015613c2e57600080fd5b509392505050565b6000828202831580613c50575082848281613c4d57fe5b04145b613c5957600080fd5b6706f05b59d3b20000810181811015613c7157600080fd5b6000670de0b6b3a764000082613c05565b600082841015613c9157600080fd5b670de0b6b3a7640000821115613ca657600080fd5b6000613cb28585613c10565b9050613cbe8184613c36565b915081811015613c2e57600080fd5b60006001831015613cdd57600080fd5b671bc16d674ec7ffff831115613cf257600080fd5b6000613cfd83613f67565b90506000613d0b8483613c10565b90506000613d2186613d1c85613f82565b613f90565b905081613d32579250611178915050565b6000613d4387846305f5e100613fe7565b9050613d4f8282613c36565b979650505050505050565b600082820183811015613ab457600080fd5b613d7682826140c5565b5050565b613d83816140d0565b50565b613d76828261414f565b6040805163a9059cbb60e01b81526001600160a01b03848116600483015260248201849052915160009286169163a9059cbb91604480830192602092919082900301818787803b158015613de357600080fd5b505af1158015613df7573d6000803e3d6000fd5b505050506040513d6020811015613e0d57600080fd5b5051905080613e1b57600080fd5b50505050565b6001600160a01b038316600090815260208190526040902054811115613e4657600080fd5b6001600160a01b038316600090815260208190526040902054613e699082613c10565b6001600160a01b038085166000908152602081905260408082209390935590841681522054613e989082613d5a565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716926000805160206141de83398151915292918290030190a3505050565b604080516323b872dd60e01b81526001600160a01b0384811660048301523060248301526044820184905291516000928616916323b872dd91606480830192602092919082900301818787803b158015613de357600080fd5b613d838161415a565b600080828410613f585750508082036000613f60565b505081810360015b9250929050565b6000670de0b6b3a7640000613f7b83613f82565b0292915050565b670de0b6b3a7640000900490565b60008060028306613fa957670de0b6b3a7640000613fab565b835b90506002830492505b8215613ab457613fc48485613c36565b93506002830615613fdc57613fd98185613c36565b90505b600283049250613fb4565b6000828180613ffe87670de0b6b3a7640000613f42565b9092509050670de0b6b3a764000080600060015b8884106140b6576000670de0b6b3a7640000820290506000806140468a61404185670de0b6b3a7640000613c10565b613f42565b9150915061405887611348848c613c36565b96506140648784613baa565b965086614073575050506140b6565b871561407d579315935b8015614087579315935b841561409e576140978688613c10565b95506140ab565b6140a88688613d5a565b95505b505050600101614012565b50909998505050505050505050565b613d76823083613e21565b306000908152602081905260409020548111156140ec57600080fd5b306000908152602081905260409020546141069082613c10565b306000908152602081905260409020556002546141239082613c10565b60025560408051828152905160009130916000805160206141de8339815191529181900360200190a350565b613d76308383613e21565b306000908152602081905260409020546141749082613d5a565b306000908152602081905260409020556002546141919082613d5a565b60025560408051828152905130916000916000805160206141de8339815191529181900360200190a35056fe63982df10efd8dfaaaa0fcc7f50b2d93b7cba26ccc48adee2873220d485dc39addf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efe74c91552b64c2e2e7bd255639e004e693bd3e1d01cc33e65610b86afcc1ffed8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925a265627a7a72315820993ab7d9193add493b90f3fbc114d124f2515ee3286bb646c67d794789a25cb064736f6c634300050c0032
[ 38 ]
0x4fea2109624a515968167d4015e54f70d28435ee
pragma solidity 0.6.9; abstract contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return balance The balance function balanceOf(address _owner) virtual public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transfer(address _to, uint256 _value) virtual public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return success Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) virtual public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return success Whether the approval was successful or not function approve(address _spender, uint256 _value) virtual public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return remaining Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) virtual public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract CartelFinance is EIP20Interface { mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; string public name = "cartel.finance"; uint8 public decimals = 4; string public symbol = "CFI"; uint256 constant private MAX_UINT256 = 2**256 - 1; constructor() public { balances[tx.origin] = 500000000; totalSupply = 500000000; } //Simple transfer function transfer(address _to, uint256 _value) override public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } //Get balance of address function balanceOf(address _owner) override public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) override public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) override public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function transferFrom(address _from, address _to, uint256 _value) override public returns (bool success) { uint256 tokenAllowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && tokenAllowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (tokenAllowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063313ce56711610071578063313ce567146101e15780635c658165146101ff57806370a082311461022d57806395d89b4114610253578063a9059cbb1461025b578063dd62ed3e14610287576100a9565b806306fdde03146100ae578063095ea7b31461012b57806318160ddd1461016b57806323b872dd1461018557806327e235e3146101bb575b600080fd5b6100b66102b5565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f05781810151838201526020016100d8565b50505050905090810190601f16801561011d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101576004803603604081101561014157600080fd5b506001600160a01b038135169060200135610343565b604080519115158252519081900360200190f35b6101736103a9565b60408051918252519081900360200190f35b6101576004803603606081101561019b57600080fd5b506001600160a01b038135811691602081013590911690604001356103af565b610173600480360360208110156101d157600080fd5b50356001600160a01b03166104b1565b6101e96104c3565b6040805160ff9092168252519081900360200190f35b6101736004803603604081101561021557600080fd5b506001600160a01b03813581169160200135166104cc565b6101736004803603602081101561024357600080fd5b50356001600160a01b03166104e9565b6100b6610504565b6101576004803603604081101561027157600080fd5b506001600160a01b03813516906020013561055f565b6101736004803603604081101561029d57600080fd5b506001600160a01b03813581169160200135166105e9565b6003805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561033b5780601f106103105761010080835404028352916020019161033b565b820191906000526020600020905b81548152906001019060200180831161031e57829003601f168201915b505050505081565b3360008181526002602090815260408083206001600160a01b038716808552908352818420869055815186815291519394909390927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925928290030190a350600192915050565b60005481565b6001600160a01b0383166000818152600260209081526040808320338452825280832054938352600190915281205490919083118015906103f05750828110155b6103f957600080fd5b6001600160a01b038085166000908152600160205260408082208054870190559187168152208054849003905560001981101561045b576001600160a01b03851660009081526002602090815260408083203384529091529020805484900390555b836001600160a01b0316856001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3506001949350505050565b60016020526000908152604090205481565b60045460ff1681565b600260209081526000928352604080842090915290825290205481565b6001600160a01b031660009081526001602052604090205490565b6005805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561033b5780601f106103105761010080835404028352916020019161033b565b3360009081526001602052604081205482111561057b57600080fd5b336000818152600160209081526040808320805487900390556001600160a01b03871680845292819020805487019055805186815290519293927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a350600192915050565b6001600160a01b0391821660009081526002602090815260408083209390941682529190915220549056fea2646970667358221220b377bc3f714b5a705d165b0bee48964bc4a50dee13c3923c487ebfa7ff804da464736f6c63430006090033
[ 38 ]
0x4FFA6aA924ca9e451f6A35319d4F5De1859D749d
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; } // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_wrappers, rates); } } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if ((_rates[i] < _rates[minIndex] && _rates[i] > 0) || _rates[minIndex] == 0) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Faucet { function gulp(address) public virtual; } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x71eC9a4fCE561c3936a511D9ebb05B60CF2bA519; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract ManagerLike { function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint wad) public { GemLike(gem).transfer(dst, wad); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } 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) { // 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) { 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); if (originationFee > 0) { ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee); } approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolCoreAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user)); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x11c937fD367D75465DC211c367684d8d4520E6f9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, msg.value, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, msg.value, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _msgValue msg.value in transaction /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _msgValue, uint256 _srcAmount) internal returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return _msgValue; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (_msgValue > _srcAmount) return _msgValue - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return _msgValue; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, _user); } else { dfsFee = getFee(_closeData.daiAmount, _user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, 0); ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount = getBalance(exchangeData.srcAddr); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { // swap (, destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, destAmount) = _sell(_data); } else { _data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr); destAmount = _data.srcAmount; } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0x948939aB1b2532C67C71292B1f955b081537c60f; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0xE7f4837F4E566eCA870b84E3455E5c85A369E3Ec; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { (, uint sellAmount) = _sell(exchangeData); getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: cAddresses[0], cDebtAddr: cAddresses[1] }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } }
0x608060405234801561001057600080fd5b50600436106101585760003560e01c8063526d6461116100c3578063870e44d91161007c578063870e44d9146102d95780638fb5a482146102e1578063bfe142a3146102f4578063cae81e6e146102fc578063d802178e1461030f578063d98bb5b11461033157610158565b8063526d64611461027b5780635c1e4172146102835780635f3bc8e714610296578063754b2707146102b65780637753f47b146102c95780637b925ab1146102d157610158565b80632b6e6581116101155780632b6e658114610203578063441697521461021657806346a0fe471461022b57806349a3d7371461024b5780634d2ab9dc1461026057806351c4a6311461026857610158565b806304aba0911461015d57806304c9805c1461018657806305a363de1461019b57806308439582146101b05780630997147d146101d05780631ec18ec0146101f0575b600080fd5b61017061016b366004612e11565b610344565b60405161017d9190613421565b60405180910390f35b61018e6103d7565b60405161017d9190613574565b6101a36103dd565b60405161017d9190613565565b6101c36101be366004612e11565b6103e2565b60405161017d91906132e9565b6101e36101de366004612cc3565b610b1f565b60405161017d9190613552565b61018e6101fe366004612d02565b611096565b61018e610211366004612d02565b6112e4565b61021e6117d0565b60405161017d9190613242565b61023e610239366004612e11565b6117e8565b60405161017d91906133be565b61025e610259366004612d02565b611b68565b005b61018e611c22565b61025e610276366004612d84565b611c28565b61021e611cb2565b61018e610291366004612d3a565b611cca565b6102a96102a4366004612e11565b612068565b60405161017d9190613289565b61018e6102c4366004612cc3565b612105565b61021e612110565b61021e612128565b61018e612140565b6101706102ef366004612e11565b61214c565b61021e6122d6565b61017061030a366004612e11565b6122e8565b61032261031d366004612dc4565b612472565b60405161017d93929190613434565b61018e61033f366004612cc3565b6126d1565b606081516001600160401b038111801561035d57600080fd5b50604051908082528060200260200182016040528015610387578160200160208202803683370190505b50905060005b82518110156103d1576103b28382815181106103a557fe5b60200260200101516126d1565b8282815181106103be57fe5b602090810291909101015260010161038d565b50919050565b61014d81565b604081565b606060006000805160206136198339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b15801561042d57600080fd5b505afa158015610441573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104659190612ce6565b905060006000805160206136198339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b1580156104b057600080fd5b505afa1580156104c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104e89190612ce6565b905083516001600160401b038111801561050157600080fd5b5060405190808252806020026020018201604052801561053b57816020015b610528612b55565b8152602001906001900390816105205790505b50925060005b8451811015610b17576000806000806000876001600160a01b0316633e1501418b888151811061056d57fe5b60200260200101516040518263ffffffff1660e01b81526004016105919190613242565b6101006040518083038186803b1580156105aa57600080fd5b505afa1580156105be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105e29190612f12565b50965096509650505094509450604051806101800160405280896001600160a01b03166334b3beee8d8a8151811061061657fe5b60200260200101516040518263ffffffff1660e01b815260040161063a9190613242565b60206040518083038186803b15801561065257600080fd5b505afa158015610666573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061068a9190612ce6565b6001600160a01b031681526020018b88815181106106a457fe5b60200260200101516001600160a01b03168152602001896001600160a01b031663c540148e8d8a815181106106d557fe5b60200260200101516040518263ffffffff1660e01b81526004016106f99190613242565b60206040518083038186803b15801561071157600080fd5b505afa158015610725573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107499190612efa565b81526020018361075a5760006107e9565b896001600160a01b031663906c0a418d8a8151811061077557fe5b60200260200101516040518263ffffffff1660e01b81526004016107999190613242565b60206040518083038186803b1580156107b157600080fd5b505afa1580156107c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107e99190612efa565b8152602001826107fa576000610889565b896001600160a01b03166388079d888d8a8151811061081557fe5b60200260200101516040518263ffffffff1660e01b81526004016108399190613242565b60206040518083038186803b15801561085157600080fd5b505afa158015610865573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108899190612efa565b8152602001896001600160a01b031663c33cfd908d8a815181106108a957fe5b60200260200101516040518263ffffffff1660e01b81526004016108cd9190613242565b60206040518083038186803b1580156108e557600080fd5b505afa1580156108f9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061091d9190612efa565b8152602001896001600160a01b031663e24030198d8a8151811061093d57fe5b60200260200101516040518263ffffffff1660e01b81526004016109619190613242565b60206040518083038186803b15801561097957600080fd5b505afa15801561098d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109b19190612efa565b8152602001896001600160a01b03166398bd47378d8a815181106109d157fe5b60200260200101516040518263ffffffff1660e01b81526004016109f59190613242565b60206040518083038186803b158015610a0d57600080fd5b505afa158015610a21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a459190612efa565b8152602001868152602001858152602001886001600160a01b031663b3596f078d8a81518110610a7157fe5b60200260200101516040518263ffffffff1660e01b8152600401610a959190613242565b60206040518083038186803b158015610aad57600080fd5b505afa158015610ac1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ae59190612efa565b8152602001841515815250898781518110610afc57fe5b60200260200101819052505050505050806001019050610541565b505050919050565b610b27612bca565b60006000805160206136198339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b7057600080fd5b505afa158015610b84573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ba89190612ce6565b905060006000805160206136198339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610bf357600080fd5b505afa158015610c07573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c2b9190612ce6565b90506060826001600160a01b0316630902f1ac6040518163ffffffff1660e01b815260040160006040518083038186803b158015610c6857600080fd5b505afa158015610c7c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052610ca49190810190612e43565b90506040518060c00160405280866001600160a01b0316815260200160006001600160801b0316815260200182516001600160401b0381118015610ce757600080fd5b50604051908082528060200260200182016040528015610d11578160200160208202803683370190505b50815260200182516001600160401b0381118015610d2e57600080fd5b50604051908082528060200260200182016040528015610d58578160200160208202803683370190505b50815260200182516001600160401b0381118015610d7557600080fd5b50604051908082528060200260200182016040528015610d9f578160200160208202803683370190505b50815260200182516001600160401b0381118015610dbc57600080fd5b50604051908082528060200260200182016040528015610de6578160200160208202803683370190505b5090529350600080805b8351816001600160401b0316101561107357600084826001600160401b031681518110610e1957fe5b60200260200101519050600080886001600160a01b03166328dd2d01848d6040518363ffffffff1660e01b8152600401610e54929190613256565b6101406040518083038186803b158015610e6d57600080fd5b505afa158015610e81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ea59190613097565b5050505050505050915091506000886001600160a01b031663b3596f0789876001600160401b031681518110610ed757fe5b60200260200101516040518263ffffffff1660e01b8152600401610efb9190613242565b60206040518083038186803b158015610f1357600080fd5b505afa158015610f27573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f4b9190612efa565b90508215610fd8576000610f5e85612810565b601203600a0a610f6e85846128b0565b029050848c60400151896001600160401b031681518110610f8b57fe5b60200260200101906001600160a01b031690816001600160a01b031681525050808c60800151896001600160401b031681518110610fc557fe5b6020908102919091010152506001909601955b8115611063576000610fe985612810565b601203600a0a610ff984846128b0565b029050848c60600151886001600160401b03168151811061101657fe5b60200260200101906001600160a01b031690816001600160a01b031681525050808c60a00151886001600160401b03168151811061105057fe5b6020908102919091010152506001909501945b505060019092019150610df09050565b5061107d876126d1565b6001600160801b0316602087015250505050505b919050565b6000806000805160206136198339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156110e057600080fd5b505afa1580156110f4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111189190612ce6565b905060006000805160206136198339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561116357600080fd5b505afa158015611177573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061119b9190612ce6565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b81526004016111cb9190613242565b6101006040518083038186803b1580156111e457600080fd5b505afa1580156111f8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061121c919061303b565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b81526004016112539190613242565b60206040518083038186803b15801561126b57600080fd5b505afa15801561127f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112a39190612efa565b90506112d76112b188612810565b601203600a0a6112c184846128e9565b816112c857fe5b04670dbd2fc137a300006128b0565b9450505050505b92915050565b6000806000805160206136198339815191526001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561132e57600080fd5b505afa158015611342573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113669190612ce6565b905060006000805160206136198339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b1580156113b157600080fd5b505afa1580156113c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113e99190612ce6565b905060006000805160206136198339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561143457600080fd5b505afa158015611448573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061146c9190612ce6565b9050600061147987612810565b601203600a0a90506000806000866001600160a01b0316632c6d0e9b8a6040518263ffffffff1660e01b81526004016114b29190613242565b6101006040518083038186803b1580156114cb57600080fd5b505afa1580156114df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115039190612fe3565b50505094505093509350506000866001600160a01b0316635fc526ff8c6040518263ffffffff1660e01b815260040161153c9190613242565b60806040518083038186803b15801561155457600080fd5b505afa158015611568573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061158c9190612fa3565b50509150506000866001600160a01b031663b3596f078d6040518263ffffffff1660e01b81526004016115bf9190613242565b60206040518083038186803b1580156115d757600080fd5b505afa1580156115eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061160f9190612efa565b90506000886001600160a01b03166318a4dbca8e8e6040518363ffffffff1660e01b8152600401611641929190613256565b60206040518083038186803b15801561165957600080fd5b505afa15801561166d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116919190612efa565b905060006116a1888302846128b0565b9050856116ba575099506112de98505050505050505050565b60006116e26116dc6116cc888b612909565b6116d78a6064612909565b61292d565b8761293d565b90508181116116f157806116f3565b815b9050878110611722578861170789866128e9565b8161170e57fe5b049c505050505050505050505050506112de565b600061173b611731888b6128b0565b6116d788866128b0565b9050600061176d61175e83611759611753888861292d565b8b6128b0565b612948565b6117688c8661292d565b6128e9565b9050878110156117ac57611798611792611787838d612909565b6116d78c6064612909565b8261293d565b92508383116117a757826117a9565b835b92505b6117ba8b6112c185896128e9565b9e50505050505050505050505050505092915050565b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b606060006000805160206136198339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b15801561183357600080fd5b505afa158015611847573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061186b9190612ce6565b905060006000805160206136198339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b1580156118b657600080fd5b505afa1580156118ca573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118ee9190612ce6565b905083516001600160401b038111801561190757600080fd5b5060405190808252806020026020018201604052801561194157816020015b61192e612c12565b8152602001906001900390816119265790505b50925060005b8451811015610b17576000836001600160a01b0316635fc526ff87848151811061196d57fe5b60200260200101516040518263ffffffff1660e01b81526004016119919190613242565b60806040518083038186803b1580156119a957600080fd5b505afa1580156119bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119e19190612fa3565b50509150506040518060800160405280856001600160a01b03166334b3beee898681518110611a0c57fe5b60200260200101516040518263ffffffff1660e01b8152600401611a309190613242565b60206040518083038186803b158015611a4857600080fd5b505afa158015611a5c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a809190612ce6565b6001600160a01b03168152602001878481518110611a9a57fe5b60200260200101516001600160a01b03168152602001828152602001846001600160a01b031663b3596f07898681518110611ad157fe5b60200260200101516040518263ffffffff1660e01b8152600401611af59190613242565b60206040518083038186803b158015611b0d57600080fd5b505afa158015611b21573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b459190612efa565b815250858381518110611b5457fe5b602090810291909101015250600101611947565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611b9d57611b98828247611c28565b611c1e565b611c1e8282846001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401611bce9190613242565b60206040518083038186803b158015611be657600080fd5b505afa158015611bfa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102769190612efa565b5050565b61019081565b80611c3257611cad565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611c93576040516001600160a01b0383169082156108fc029083906000818181858888f19350505050158015611c8d573d6000803e3d6000fd5b50611cad565b611cad6001600160a01b038416838363ffffffff61295816565b505050565b73637726f8b08a7abe3ae3acab01a80e2d8ddef77b81565b6000806000805160206136198339815191526001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b158015611d1457600080fd5b505afa158015611d28573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d4c9190612ce6565b905060006000805160206136198339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015611d9757600080fd5b505afa158015611dab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dcf9190612ce6565b905060006000805160206136198339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015611e1a57600080fd5b505afa158015611e2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e529190612ce6565b90506000806000856001600160a01b0316632c6d0e9b896040518263ffffffff1660e01b8152600401611e859190613242565b6101006040518083038186803b158015611e9e57600080fd5b505afa158015611eb2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ed69190612fe3565b50505094505093509350506000856001600160a01b0316635fc526ff8b6040518263ffffffff1660e01b8152600401611f0f9190613242565b60806040518083038186803b158015611f2757600080fd5b505afa158015611f3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f5f9190612fa3565b5050915050611f78611f718584612909565b606461293d565b93506000611fb4611fa6611f9f611f8f888861292d565b611f9a60648761292d565b61293d565b6064612909565b670dbd2fc137a300006128b0565b90506000866001600160a01b031663b3596f078e6040518263ffffffff1660e01b8152600401611fe49190613242565b60206040518083038186803b158015611ffc57600080fd5b505afa158015612010573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120349190612efa565b905061203f8d612810565b601203600a0a61204f83836128e9565b8161205657fe5b049d9c50505050505050505050505050565b606081516001600160401b038111801561208157600080fd5b506040519080825280602002602001820160405280156120bb57816020015b6120a8612bca565b8152602001906001900390816120a05790505b50905060005b82518110156103d1576120e68382815181106120d957fe5b6020026020010151610b1f565b8282815181106120f257fe5b60209081029190910101526001016120c1565b60006112de826126d1565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b731b14e8d511c9a4395425314f849bd737baf8208f81565b670dbd2fc137a3000081565b606060006000805160206136198339815191526001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561219757600080fd5b505afa1580156121ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121cf9190612ce6565b905082516001600160401b03811180156121e857600080fd5b50604051908082528060200260200182016040528015612212578160200160208202803683370190505b50915060005b83518110156122cf57816001600160a01b031663b3596f0785838151811061223c57fe5b60200260200101516040518263ffffffff1660e01b81526004016122609190613242565b60206040518083038186803b15801561227857600080fd5b505afa15801561228c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122b09190612efa565b8382815181106122bc57fe5b6020908102919091010152600101612218565b5050919050565b60008051602061361983398151915281565b606060006000805160206136198339815191526001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b15801561233357600080fd5b505afa158015612347573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061236b9190612ce6565b905082516001600160401b038111801561238457600080fd5b506040519080825280602002602001820160405280156123ae578160200160208202803683370190505b50915060005b83518110156122cf57816001600160a01b0316635fc526ff8583815181106123d857fe5b60200260200101516040518263ffffffff1660e01b81526004016123fc9190613242565b60806040518083038186803b15801561241457600080fd5b505afa158015612428573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061244c9190612fa3565b9091925090505083828151811061245f57fe5b60209081029190910101526001016123b4565b606080606060006000805160206136198339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156124c057600080fd5b505afa1580156124d4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124f89190612ce6565b905084516001600160401b038111801561251157600080fd5b5060405190808252806020026020018201604052801561253b578160200160208202803683370190505b50935084516001600160401b038111801561255557600080fd5b5060405190808252806020026020018201604052801561257f578160200160208202803683370190505b50925084516001600160401b038111801561259957600080fd5b506040519080825280602002602001820160405280156125c3578160200160208202803683370190505b50915060005b85518110156126c85760008682815181106125e057fe5b60200260200101519050826001600160a01b03166328dd2d01828a6040518363ffffffff1660e01b8152600401612618929190613256565b6101406040518083038186803b15801561263157600080fd5b505afa158015612645573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126699190613097565b8f519097508f96508b9550851093506126829250505057fe5b6020026020010188868151811061269557fe5b602002602001018887815181106126a857fe5b9315156020948502919091019093019290925291905252506001016125c9565b50509250925092565b6000806000805160206136198339815191526001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b15801561271b57600080fd5b505afa15801561272f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127539190612ce6565b9050600080826001600160a01b031663bf92857c866040518263ffffffff1660e01b81526004016127849190613242565b6101006040518083038186803b15801561279d57600080fd5b505afa1580156127b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127d5919061303b565b5050509450509350505081600014156127f45760009350505050611091565b6128076128018383612948565b836128e9565b95945050505050565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee141561283f57506012611091565b816001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561287857600080fd5b505afa15801561288c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112de9190612efa565b6000670de0b6b3a76400006128da6128c88585612909565b6002670de0b6b3a76400005b04612948565b816128e157fe5b049392505050565b6000816128da61290185670de0b6b3a7640000612909565b6002856128d4565b60008115806129245750508082028282828161292157fe5b04145b6112de57600080fd5b808203828111156112de57600080fd5b60008183816128e157fe5b808201828110156112de57600080fd5b611cad8363a9059cbb60e01b8484604051602401612977929190613270565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b03199093169290921790915260606129fe826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612a419092919063ffffffff16565b805190915015611cad5780806020019051810190612a1c9190612ede565b611cad5760405162461bcd60e51b8152600401612a3890613508565b60405180910390fd5b6060612a508484600085612a58565b949350505050565b6060612a6385612b1c565b612a7f5760405162461bcd60e51b8152600401612a38906134d1565b60006060866001600160a01b03168587604051612a9c9190613226565b60006040518083038185875af1925050503d8060008114612ad9576040519150601f19603f3d011682016040523d82523d6000602084013e612ade565b606091505b50915091508115612af2579150612a509050565b805115612b025780518082602001fd5b8360405162461bcd60e51b8152600401612a38919061349e565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590612a50575050151592915050565b60405180610180016040528060006001600160a01b0316815260200160006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000151581525090565b6040518060c0016040528060006001600160a01b0316815260200160006001600160801b03168152602001606081526020016060815260200160608152602001606081525090565b604051806080016040528060006001600160a01b0316815260200160006001600160a01b0316815260200160008152602001600081525090565b600082601f830112612c5c578081fd5b8135612c6f612c6a826135a3565b61357d565b818152915060208083019084810181840286018201871015612c9057600080fd5b60005b84811015612cb8578135612ca6816135f2565b84529282019290820190600101612c93565b505050505092915050565b600060208284031215612cd4578081fd5b8135612cdf816135f2565b9392505050565b600060208284031215612cf7578081fd5b8151612cdf816135f2565b60008060408385031215612d14578081fd5b8235612d1f816135f2565b91506020830135612d2f816135f2565b809150509250929050565b600080600060608486031215612d4e578081fd5b8335612d59816135f2565b92506020840135612d69816135f2565b91506040840135612d79816135f2565b809150509250925092565b600080600060608486031215612d98578283fd5b8335612da3816135f2565b92506020840135612db3816135f2565b929592945050506040919091013590565b60008060408385031215612dd6578182fd5b8235612de1816135f2565b915060208301356001600160401b03811115612dfb578182fd5b612e0785828601612c4c565b9150509250929050565b600060208284031215612e22578081fd5b81356001600160401b03811115612e37578182fd5b612a5084828501612c4c565b60006020808385031215612e55578182fd5b82516001600160401b03811115612e6a578283fd5b80840185601f820112612e7b578384fd5b80519150612e8b612c6a836135a3565b8281528381019082850185850284018601891015612ea7578687fd5b8693505b84841015612ed2578051612ebe816135f2565b835260019390930192918501918501612eab565b50979650505050505050565b600060208284031215612eef578081fd5b8151612cdf8161360a565b600060208284031215612f0b578081fd5b5051919050565b600080600080600080600080610100898b031215612f2e578384fd5b8851975060208901519650604089015195506060890151612f4e816135f2565b60808a0151909550612f5f8161360a565b60a08a0151909450612f708161360a565b60c08a0151909350612f818161360a565b60e08a0151909250612f928161360a565b809150509295985092959890939650565b60008060008060808587031215612fb8578384fd5b8451935060208501519250604085015191506060850151612fd88161360a565b939692955090935050565b600080600080600080600080610100898b031215612fff578182fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e0890151612f928161360a565b600080600080600080600080610100898b031215613057578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6000806000806000806000806000806101408b8d0312156130b6578384fd5b8a51995060208b0151985060408b0151975060608b0151965060808b0151955060a08b0151945060c08b0151935060e08b015192506101008b015191506101208b01518015158114613106578182fd5b809150509295989b9194979a5092959850565b6001600160a01b03169052565b6000815180845260208085019450808401835b8381101561315e5781516001600160a01b031687529582019590820190600101613139565b509495945050505050565b6000815180845260208085019450808401835b8381101561315e5781518752958201959082019060010161317c565b15159052565b600060018060a01b0382511683526001600160801b036020830151166020840152604082015160c060408501526131d860c0850182613126565b6060840151915084810360608601526131f18183613126565b60808501519250858103608087015261320a8184613169565b91505060a0840151915084810360a08601526128078183613169565b600082516132388184602087016135c2565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03929092168252602082015260400190565b6000602080830181845280855180835260408601915060408482028701019250838701855b828110156132dc57603f198886030184526132ca85835161319e565b945092850192908501906001016132ae565b5092979650505050505050565b602080825282518282018190526000919060409081850190868401855b828110156133b157815161331b858251613119565b8681015161332b88870182613119565b508086015185870152606080820151908601526080808201519086015260a0808201519086015260c0808201519086015260e080820151908601526101008082015190860152610120808201519086015261014080820151908601526101608082015161339a82880182613198565b505050610180939093019290850190600101613306565b5091979650505050505050565b602080825282518282018190526000919060409081850190868401855b828110156133b157815180516001600160a01b039081168652878201511687860152858101518686015260609081015190850152608090930192908501906001016133db565b600060208252612cdf6020830184613169565b6000606082526134476060830186613169565b60208382038185015261345a8287613169565b84810360408601528551808252908201925081860190845b81811015613490578251151585529383019391830191600101613472565b509298975050505050505050565b60006020825282518060208401526134bd8160408501602087016135c2565b601f01601f19169190910160400192915050565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b600060208252612cdf602083018461319e565b61ffff91909116815260200190565b90815260200190565b6040518181016001600160401b038111828210171561359b57600080fd5b604052919050565b60006001600160401b038211156135b8578081fd5b5060209081020190565b60005b838110156135dd5781810151838201526020016135c5565b838111156135ec576000848401525b50505050565b6001600160a01b038116811461360757600080fd5b50565b801515811461360757600080fdfe00000000000000000000000024a42fd28c976a61df5d00d0599c34c4f90748c8a2646970667358221220bbfe64ec01e36d5198be259fb89fd308da9d0d210c3503e760a2f34ea921a6da64736f6c63430006060033
[ 21, 37, 17, 11, 8, 9, 12, 16, 5, 2 ]
0x507ae33c5a059cb22217bad9fb2a9d929908866e
pragma solidity 0.6.6; 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; } } 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; } function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a, m); uint256 d = sub(c, 1); return mul(div(d,m),m); } } interface IKEK { function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function burn(address account, uint256 amount) external; } interface IFARMINGPOOL { function getTotalStakedAmount() external view returns (uint256); function getStakedAmount(address account) external view returns (uint256); function getStakers() external view returns (address[] memory); } contract StakingReward is Context { using SafeMath for uint256; // Events event ClaimedReward(address account, uint256 amount); // states struct Gains { uint256 RPEPEBLUPendingGains; uint256 RPEPELPURPLEPendingGains; uint256 RPEPEBLUTotalGained; uint256 RPEPELPURPLETotalGained; } address private _RPEPEBLU; address private _RPEPELPURPLE; address private _KEK; uint private _lastTimestamp; uint private _timeInterval; uint256 private _rewardBlockAmount; uint256 private _totalRewardsPerDay; mapping(address => Gains) private _gains; constructor(address kek, address rpepeblu, address rpepelpurple, uint timeInterval) public { _KEK = kek; _RPEPEBLU = rpepeblu; _RPEPELPURPLE = rpepelpurple; // Set the initial last timestamp _lastTimestamp = block.timestamp; // Set the initial staking reward block size _rewardBlockAmount = 260000E18; // time interval for create reward block and claim reward // This value will be 1 day _timeInterval = timeInterval; } /** * @dev API to get reward block size */ function getRewardBlockAmount() external view returns (uint256) { return _rewardBlockAmount; } /** * @dev API to get the staker's pending gains in RPEPEBLU pool */ function getPendingGainsInRPEPEBLU(address account) public view returns (uint256) { return _gains[account].RPEPEBLUPendingGains; } /** * @dev API to get the staker's pending gains in RPEPELPURPLE pool */ function getPendingGainsInRPEPELPURPLE(address account) public view returns (uint256) { return _gains[account].RPEPELPURPLEPendingGains; } /** * @dev API to get the staker's total gained in RPEPEBLU pool */ function getTotalGainedInRPEPEBLU(address account) public view returns (uint256) { return _gains[account].RPEPEBLUTotalGained; } /** * @dev API to get the staker's total gained in RPEPELPURPLE pool */ function getTotalGainedInRPEPELPURPLE(address account) public view returns (uint256) { return _gains[account].RPEPELPURPLETotalGained; } /** * @dev API to get total amount staked in RPEPEBLU and RPEPELPURPLE pools */ function getTotalStakedAmountInPools() public view returns (uint256) { uint256 stakedAmountInPKPool = IFARMINGPOOL(_RPEPEBLU).getTotalStakedAmount(); uint256 stakedAmountInLPPool = IFARMINGPOOL(_RPEPELPURPLE).getTotalStakedAmount(); return stakedAmountInPKPool.add(stakedAmountInLPPool); } /** * @dev API to get current daily staking rate of RPEPEBLU pool. * * Algorithm * - rate = (block size / 2) / amount of rPEPE in RPEPEBLU and RPEPELPURPLE pools. * - if block size = 260,000KEK (phase 1) * then maximum rate=0.05KEK, minimum rate=0.005KEK * - if block size = 130,000KEK (phase 2) * then maximum rate=0.025KEK, minimum rate=0.0025KEK * - if block size = 65,000KEK (phase 3) * then maximum rate=0.0125KEK, minimum rate=0.00125KEK * - if block size = 32,500KEK (phase 4) * then maximum rate=0.00625KEK, minimum rate=0.000625KEK */ function getStakingRateInRPEPEBLU() public view returns (uint256) { uint256 maxRate = _getMaximunRate(); uint256 minRate = _getMinimunRate(); uint256 totalStakedAmount = getTotalStakedAmountInPools(); uint256 rate = 0; if (totalStakedAmount > 0) { rate = _rewardBlockAmount.mul(1E18).div(totalStakedAmount); if (rate < minRate) { rate = minRate; } else if (rate > maxRate) { rate = maxRate; } } return rate; } /** * @dev API to get current daily staking rate of RPEPELPURPLE pool. * * Algorithm * - rate = block size / amount of rPEPE in RPEPEBLU and RPEPELPURPLE pools * - if block size = 260,000KEK (phase 1) * then maximum rate=0.1KEK, minimum rate=0.01KEK * - if block size = 130,000KEK (phase 2) * then maximum rate=0.05KEK, minimum rate=0.005KEK * - if block size = 65,000KEK (phase 3) * then maximum rate=0.025KEK, minimum rate=0.0025KEK * - if block size = 32,500KEK (phase 4) * then maximum rate=0.0125KEK, minimum rate=0.00125KEK */ function getStakingRateInRPEPELPURPLE() public view returns (uint256) { uint256 maxRate = _getMaximunRate().mul(2); uint256 minRate = _getMinimunRate().mul(2); uint256 totalStakedAmount = getTotalStakedAmountInPools(); uint256 rate = 0; if (totalStakedAmount > 0) { rate = _rewardBlockAmount.mul(1E18).div(totalStakedAmount); if (rate < minRate) { rate = minRate; } else if (rate > maxRate) { rate = maxRate; } } return rate; } /** * @dev API to harvest staker's reward from RPEPEBLU. */ function harvestFromRPEPEBLU() external { uint256 pendingGains = getPendingGainsInRPEPEBLU(_msgSender()); // send tokens to the staker's account require(IKEK(_KEK).transfer(_msgSender(), pendingGains)); _gains[_msgSender()].RPEPEBLUPendingGains = 0; _gains[_msgSender()].RPEPEBLUTotalGained = _gains[_msgSender()].RPEPEBLUTotalGained.add(pendingGains); emit ClaimedReward(_msgSender(), pendingGains); } /** * @dev API to harvest staker's reward from RPEPELPURPLE. */ function harvestFromRPEPELPURPLE() external { uint256 pendingGains = getPendingGainsInRPEPELPURPLE(_msgSender()); // send tokens to the staker's account require(IKEK(_KEK).transfer(_msgSender(), pendingGains)); _gains[_msgSender()].RPEPELPURPLEPendingGains = 0; _gains[_msgSender()].RPEPELPURPLETotalGained = _gains[_msgSender()].RPEPELPURPLETotalGained.add(pendingGains); emit ClaimedReward(_msgSender(), pendingGains); } /** * @dev API to create new staking reward block and claim reward per day. */ function createRewardBlockAndClaimRewards() external { uint count = (block.timestamp - _lastTimestamp) / _timeInterval; _createRewardBlockAndClaimRewards(count); // update last timestamp _lastTimestamp = count * _timeInterval + _lastTimestamp; } /** * @dev Get maximum rate */ function _getMaximunRate() internal view returns (uint256) { uint256 maxRate = 0; if (_rewardBlockAmount == 260000E18) { // for phase 1 maxRate = 5E16; } else if (_rewardBlockAmount == 130000E18) { // for phase 2 maxRate = 25E15; } else if (_rewardBlockAmount == 65000E18) { // for phase 3 maxRate = 125E14; } else if (_rewardBlockAmount == 32500E18) { // for phase 4 maxRate = 625E13; } require(maxRate > 0, "Block size has been undefined"); return maxRate; } /** * @dev Get minimum rate */ function _getMinimunRate() internal view returns (uint256) { uint256 minRate = 0; if (_rewardBlockAmount == 260000E18) { // for phase 1 minRate = 5E15; } else if (_rewardBlockAmount == 130000E18) { // for phase 2 minRate = 25E14; } else if (_rewardBlockAmount == 65000E18) { // for phase 3 minRate = 125E13; } else if (_rewardBlockAmount == 32500E18) { // for phase 4 minRate = 625E12; } require(minRate > 0, "Block size has been undefined"); return minRate; } /** * @dev Create new staking reward block by calculation the remaining in staking reward. */ function _createRewardBlockAndClaimRewards(uint count) internal { for (uint i = 0; i < count; i++) { _createRewardBlockAndBurn(IKEK(_KEK).balanceOf(address(this))); _claimRewardsInRPEPEBLU(); _claimRewardsInRPEPELPURPLE(); } } /** * @dev Set the block amount for current staking reward and burn tokens for block amount * * Formula: * - 260,000 KEK (75%-100% remaining in staking reward) * - 130,000 KEK (50%-75% remaining in staking reward) * - 65,000 KEK (25%-50% remaining in staking reward) * - 32,500 KEK (0%-25% remaining in staking reward) */ function _createRewardBlockAndBurn(uint256 available) internal { require(available > 0, "Available KEK amount must be more than zero."); uint256 percent = available.div(49000000E10).mul(100); // Initialize total rewards per day _totalRewardsPerDay = 0; if (percent > 0 && percent < 25) { _rewardBlockAmount = 32500E18; IKEK(_KEK).burn(address(this), 32500E18); } else if (percent >= 25 && percent < 50) { _rewardBlockAmount = 65000E18; IKEK(_KEK).burn(address(this), 65000E18); } else if (percent >= 50 && percent < 75) { _rewardBlockAmount = 130000E18; IKEK(_KEK).burn(address(this), 130000E18); } else if (percent >= 75 && percent <= 100) { _rewardBlockAmount = 260000E18; IKEK(_KEK).burn(address(this), 260000E18); } } /** * @dev Claim rewards to all stakers in RPEPEBLU daily */ function _claimRewardsInRPEPEBLU() internal { address[] memory stakers = IFARMINGPOOL(_RPEPEBLU).getStakers(); for (uint256 i = 0; i < stakers.length; i++) { _calcPendingGainsInRPEPEBLU(stakers[i]); } } /** * @dev Claim rewards to all stakers in RPEPELPURPLE daily */ function _claimRewardsInRPEPELPURPLE() internal { address[] memory stakers = IFARMINGPOOL(_RPEPELPURPLE).getStakers(); for (uint256 i = 0; i < stakers.length; i++) { _calcPendingGainsInRPEPELPURPLE(stakers[i]); } } /** * @dev Calcuate staker's pending gains in RPEPEBLU. */ function _calcPendingGainsInRPEPEBLU(address account) internal { require(account != address(0), "Invalid address"); uint256 rewards = (IFARMINGPOOL(_RPEPEBLU).getStakedAmount(account)).mul(getStakingRateInRPEPEBLU()).div(1E18); if (_totalRewardsPerDay.add(rewards) > _rewardBlockAmount) { rewards = _rewardBlockAmount.sub(_totalRewardsPerDay); } _gains[account].RPEPEBLUPendingGains = _gains[account].RPEPEBLUPendingGains.add(rewards); _totalRewardsPerDay = _totalRewardsPerDay.add(rewards); } /** * @dev Calcuate staker's pending gains in RPEPELPURPLE. */ function _calcPendingGainsInRPEPELPURPLE(address account) internal { require(account != address(0), "Invalid address"); uint256 rewards = (IFARMINGPOOL(_RPEPELPURPLE).getStakedAmount(account)).mul(getStakingRateInRPEPELPURPLE()).div(1E18); if (_totalRewardsPerDay.add(rewards) > _rewardBlockAmount) { rewards = _rewardBlockAmount.sub(_totalRewardsPerDay); } _gains[account].RPEPELPURPLEPendingGains = _gains[account].RPEPELPURPLEPendingGains.add(rewards); _totalRewardsPerDay = _totalRewardsPerDay.add(rewards); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c8063b6301ba411610071578063b6301ba414610156578063c430074b146101ae578063da861c78146101cc578063e7b64fe314610224578063e7d5062f14610242578063fe8787dd1461024c576100a9565b8063072e6de4146100ae5780632cc54d6f146101065780633a4c15311461012457806368ac9d031461012e57806388d691d214610138575b600080fd5b6100f0600480360360208110156100c457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506102a4565b6040518082815260200191505060405180910390f35b61010e6102f0565b6040518082815260200191505060405180910390f35b61012c61037c565b005b6101366105f1565b005b610140610620565b6040518082815260200191505060405180910390f35b6101986004803603602081101561016c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610788565b6040518082815260200191505060405180910390f35b6101b66107d4565b6040518082815260200191505060405180910390f35b61020e600480360360208110156101e257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506107de565b6040518082815260200191505060405180910390f35b61022c61082a565b6040518082815260200191505060405180910390f35b61024a6108dc565b005b61028e6004803603602081101561026257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610b51565b6040518082815260200191505060405180910390f35b6000600760008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001549050919050565b6000806102fb610b9d565b90506000610307610cac565b90506000610313610620565b9050600080905060008211156103725761035282610344670de0b6b3a7640000600554610dbb90919063ffffffff16565b610e4190919063ffffffff16565b90508281101561036457829050610371565b83811115610370578390505b5b5b8094505050505090565b600061038e610389610e8b565b610b51565b9050600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb6103d6610e8b565b836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561044057600080fd5b505af1158015610454573d6000803e3d6000fd5b505050506040513d602081101561046a57600080fd5b810190808051906020019092919050505061048457600080fd5b600060076000610492610e8b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206001018190555061052f81600760006104e3610e8b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060030154610e9390919063ffffffff16565b6007600061053b610e8b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600301819055507fd0813ff03c470dcc7baa9ce36914dc2febdfd276d639deffaac383fd3db42ba36105a5610e8b565b82604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a150565b600060045460035442038161060257fe5b04905061060e81610f1b565b60035460045482020160038190555050565b6000806000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338adb6f06040518163ffffffff1660e01b815260040160206040518083038186803b15801561068a57600080fd5b505afa15801561069e573d6000803e3d6000fd5b505050506040513d60208110156106b457600080fd5b810190808051906020019092919050505090506000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166338adb6f06040518163ffffffff1660e01b815260040160206040518083038186803b15801561073157600080fd5b505afa158015610745573d6000803e3d6000fd5b505050506040513d602081101561075b57600080fd5b810190808051906020019092919050505090506107818183610e9390919063ffffffff16565b9250505090565b6000600760008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600301549050919050565b6000600554905090565b6000600760008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600201549050919050565b600080610848600261083a610b9d565b610dbb90919063ffffffff16565b905060006108676002610859610cac565b610dbb90919063ffffffff16565b90506000610873610620565b9050600080905060008211156108d2576108b2826108a4670de0b6b3a7640000600554610dbb90919063ffffffff16565b610e4190919063ffffffff16565b9050828110156108c4578290506108d1565b838111156108d0578390505b5b5b8094505050505090565b60006108ee6108e9610e8b565b6102a4565b9050600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb610936610e8b565b836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156109a057600080fd5b505af11580156109b4573d6000803e3d6000fd5b505050506040513d60208110156109ca57600080fd5b81019080805190602001909291905050506109e457600080fd5b6000600760006109f2610e8b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000181905550610a8f8160076000610a43610e8b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060020154610e9390919063ffffffff16565b60076000610a9b610e8b565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600201819055507fd0813ff03c470dcc7baa9ce36914dc2febdfd276d639deffaac383fd3db42ba3610b05610e8b565b82604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a150565b6000600760008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600101549050919050565b6000806000905069370ea0d47cf61a8000006005541415610bc75766b1a2bc2ec500009050610c2f565b691b87506a3e7b0d4000006005541415610bea576658d15e176280009050610c2e565b690dc3a8351f3d86a000006005541415610c0d57662c68af0bb140009050610c2d565b6906e1d41a8f9ec35000006005541415610c2c576616345785d8a00090505b5b5b5b60008111610ca5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f426c6f636b2073697a6520686173206265656e20756e646566696e656400000081525060200191505060405180910390fd5b8091505090565b6000806000905069370ea0d47cf61a8000006005541415610cd6576611c37937e080009050610d3e565b691b87506a3e7b0d4000006005541415610cf9576608e1bc9bf040009050610d3d565b690dc3a8351f3d86a000006005541415610d1c57660470de4df820009050610d3c565b6906e1d41a8f9ec35000006005541415610d3b576602386f26fc100090505b5b5b5b60008111610db4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601d8152602001807f426c6f636b2073697a6520686173206265656e20756e646566696e656400000081525060200191505060405180910390fd5b8091505090565b600080831415610dce5760009050610e3b565b6000828402905082848281610ddf57fe5b0414610e36576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180611eb36021913960400191505060405180910390fd5b809150505b92915050565b6000610e8383836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061102c565b905092915050565b600033905090565b600080828401905083811015610f11576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b60008090505b818110156110285761100b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610fcb57600080fd5b505afa158015610fdf573d6000803e3d6000fd5b505050506040513d6020811015610ff557600080fd5b81019080805190602001909291905050506110f2565b611013611564565b61101b6116e0565b8080600101915050610f21565b5050565b600080831182906110d8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561109d578082015181840152602081019050611082565b50505050905090810190601f1680156110ca5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385816110e457fe5b049050809150509392505050565b6000811161114b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c815260200180611ed4602c913960400191505060405180910390fd5b600061117b606461116d6706ccd46763f1000085610e4190919063ffffffff16565b610dbb90919063ffffffff16565b905060006006819055506000811180156111955750601981105b1561127b576906e1d41a8f9ec3500000600581905550600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16639dc29fac306906e1d41a8f9ec35000006040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b15801561125e57600080fd5b505af1158015611272573d6000803e3d6000fd5b50505050611560565b6019811015801561128c5750603281105b1561137257690dc3a8351f3d86a00000600581905550600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16639dc29fac30690dc3a8351f3d86a000006040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b15801561135557600080fd5b505af1158015611369573d6000803e3d6000fd5b5050505061155f565b603281101580156113835750604b81105b1561146957691b87506a3e7b0d400000600581905550600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16639dc29fac30691b87506a3e7b0d4000006040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b15801561144c57600080fd5b505af1158015611460573d6000803e3d6000fd5b5050505061155e565b604b811015801561147b575060648111155b1561155d5769370ea0d47cf61a800000600581905550600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16639dc29fac3069370ea0d47cf61a8000006040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050600060405180830381600087803b15801561154457600080fd5b505af1158015611558573d6000803e3d6000fd5b505050505b5b5b5b5050565b60606000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166343352d616040518163ffffffff1660e01b815260040160006040518083038186803b1580156115cd57600080fd5b505afa1580156115e1573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f82011682018060405250602081101561160b57600080fd5b810190808051604051939291908464010000000082111561162b57600080fd5b8382019150602082018581111561164157600080fd5b825186602082028301116401000000008211171561165e57600080fd5b8083526020830192505050908051906020019060200280838360005b8381101561169557808201518184015260208101905061167a565b50505050905001604052505050905060008090505b81518110156116dc576116cf8282815181106116c257fe5b602002602001015161185d565b80806001019150506116aa565b5050565b6060600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166343352d616040518163ffffffff1660e01b815260040160006040518083038186803b15801561174a57600080fd5b505afa15801561175e573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f82011682018060405250602081101561178857600080fd5b81019080805160405193929190846401000000008211156117a857600080fd5b838201915060208201858111156117be57600080fd5b82518660208202830111640100000000821117156117db57600080fd5b8083526020830192505050908051906020019060200280838360005b838110156118125780820151818401526020810190506117f7565b50505050905001604052505050905060008090505b81518110156118595761184c82828151811061183f57fe5b6020026020010151611b02565b8080600101915050611827565b5050565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415611900576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600f8152602001807f496e76616c69642061646472657373000000000000000000000000000000000081525060200191505060405180910390fd5b6000611a0e670de0b6b3a7640000611a006119196102f0565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16634da6a556876040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156119b757600080fd5b505afa1580156119cb573d6000803e3d6000fd5b505050506040513d60208110156119e157600080fd5b8101908080519060200190929190505050610dbb90919063ffffffff16565b610e4190919063ffffffff16565b9050600554611a2882600654610e9390919063ffffffff16565b1115611a4857611a45600654600554611da890919063ffffffff16565b90505b611a9d81600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000154610e9390919063ffffffff16565b600760008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000181905550611af881600654610e9390919063ffffffff16565b6006819055505050565b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415611ba5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600f8152602001807f496e76616c69642061646472657373000000000000000000000000000000000081525060200191505060405180910390fd5b6000611cb4670de0b6b3a7640000611ca6611bbe61082a565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16634da6a556876040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015611c5d57600080fd5b505afa158015611c71573d6000803e3d6000fd5b505050506040513d6020811015611c8757600080fd5b8101908080519060200190929190505050610dbb90919063ffffffff16565b610e4190919063ffffffff16565b9050600554611cce82600654610e9390919063ffffffff16565b1115611cee57611ceb600654600554611da890919063ffffffff16565b90505b611d4381600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060010154610e9390919063ffffffff16565b600760008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060010181905550611d9e81600654610e9390919063ffffffff16565b6006819055505050565b6000611dea83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611df2565b905092915050565b6000838311158290611e9f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611e64578082015181840152602081019050611e49565b50505050905090810190601f168015611e915780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838503905080915050939250505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77417661696c61626c65204b454b20616d6f756e74206d757374206265206d6f7265207468616e207a65726f2ea2646970667358221220d0c8ed8ebc174094fe7fb10d3be2768f12166370a0374578c542e600f71c221264736f6c63430006060033
[ 4, 7 ]
0x50950C6767A4F9e5EE29c6634aCa1f34505166d5
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; interface PotLike { function chi() external view returns (uint); function pie(address) external view returns (uint); function drip() external returns (uint); function join(uint) external; function exit(uint) external; } interface GemLike { function approve(address, uint) external; function balanceOf(address) external view returns (uint); function transferFrom(address, address, uint) external returns (bool); } interface VatLike { function dai(address) external view returns (uint); function hope(address) external; } interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract CDelegateInterface is CDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Cheese { /// @notice EIP-20 token name for this token string public constant name = "CHS"; /// @notice EIP-20 token symbol for this token string public constant symbol = "CHS"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public constant totalSupply = 10000000e18; // 10 million Comp /// @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; /// @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint256 amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Construct a new Comp token * @param account The initial account to grant all the tokens */ constructor(address account) public { balances[account] = uint96(totalSupply); emit Transfer(address(0), account, totalSupply); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external returns (bool) { uint96 amount; if (rawAmount == uint(-1)) { amount = uint96(-1); } else { amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external returns (bool) { uint96 amount = safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != uint96(-1)) { uint96 newAllowance = sub96(spenderAllowance, amount, "Comp::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "Comp::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "Comp::delegateBySig: invalid nonce"); require(now <= expiry, "Comp::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint96) { require(blockNumber < block.number, "Comp::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "Comp::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "Comp::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "Comp::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "Comp::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "Comp::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "Comp::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "Comp::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } contract UnitrollerAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of Unitroller */ address public comptrollerImplementation; /** * @notice Pending brains of Unitroller */ address public pendingComptrollerImplementation; } contract ComptrollerV1Storage is UnitrollerAdminStorage { /** * @notice Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @notice Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @notice Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => CToken[]) public accountAssets; } contract ComptrollerV2Storage is ComptrollerV1Storage { struct Market { /// @notice Whether or not this market is listed bool isListed; /** * @notice Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be between 0 and 1, and stored as a mantissa. */ uint collateralFactorMantissa; /// @notice Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; /// @notice Whether or not this market receives COMP bool isComped; } /** * @notice Official mapping of cTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @notice The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract ComptrollerV3Storage is ComptrollerV2Storage { struct CompMarketState { /// @notice The market's last updated compBorrowIndex or compSupplyIndex uint224 index; /// @notice The block number the index was last updated at uint32 block; } /// @notice A list of all markets CToken[] public allMarkets; /// @notice The rate at which the flywheel distributes COMP, per block uint public compRate; /// @notice The portion of compRate that each market currently receives mapping(address => uint) public compSpeeds; /// @notice The mining cheese rule, 0 - minting by supply, 1 - minting by borrow uint public miningRule; /// @notice The COMP market supply state for each market mapping(address => CompMarketState) public compSupplyState; /// @notice The COMP market borrow state for each market mapping(address => CompMarketState) public compBorrowState; /// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compSupplierIndex; /// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP mapping(address => mapping(address => uint)) public compBorrowerIndex; /// @notice The COMP accrued but not yet transferred to each user mapping(address => uint) public compAccrued; /// @notice The mining CHEESE Buff mapping(address => uint) public miningBuff; } interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } interface EIP20NonStandardInterface { /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer */ function transferFrom(address src, address dst, uint256 amount) external; /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, COMPTROLLER_REJECTION, COMPTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_COMPTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_COMPTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_COMPTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_COMPTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amnount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } contract PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; /** * @notice Get the underlying price of a cToken asset * @param sToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CToken sToken) external view returns (uint); function getUnderlyingPriceWithoutScale(CToken sToken) external view returns (uint); } 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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction underflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter { /** * @notice Emitted when pendingComptrollerImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = comptrollerImplementation; address oldPendingImplementation = pendingComptrollerImplementation; comptrollerImplementation = pendingComptrollerImplementation; pendingComptrollerImplementation = address(0); emit NewImplementation(oldImplementation, comptrollerImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = comptrollerImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } contract CErc20Delegator is CTokenInterface, CErc20Interface, CDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "CErc20Delegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { borrower; repayAmount; cTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { newComptroller; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"CErc20Delegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } } contract CToken is CTokenInterface, Exponential, TokenErrorReporter { /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting interest rate model failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srcTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); comptroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance could not be calculated"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { uint cTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calculate block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives cTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems cTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ if (repayAmount == uint(-1)) { vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = cTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "add reserves unexpected overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential { /// @notice Emitted when an admin supports a market event MarketListed(CToken cToken); /// @notice Emitted when an account enters a market event MarketEntered(CToken cToken, address account); /// @notice Emitted when an account exits a market event MarketExited(CToken cToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when maxAssets is changed by admin event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event MarketActionPaused(CToken cToken, string action, bool pauseState); /// @notice Emitted when market comped status is changed event MarketComped(CToken cToken, bool isComped); /// @notice Emitted when COMP rate is changed event NewCompRate(uint oldCompRate, uint newCompRate); /// @notice Emitted when a new COMP speed is calculated for a market event CompSpeedUpdated(CToken indexed cToken, uint newSpeed, uint totalUtility, uint utility); /// @notice Emitted when COMP is distributed to a supplier event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex); /// @notice Emitted when COMP is distributed to a borrower event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex); /// @notice The threshold above which the flywheel transfers COMP, in wei //uint public constant compClaimThreshold = 0.001e18; uint public constant compClaimThreshold = 1e18; /// @notice The initial COMP index for a market uint224 public constant compInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // liquidationIncentiveMantissa must be no less than this value uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 constructor() public { admin = msg.sender; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (CToken[] memory) { CToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param cToken The cToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, CToken cToken) external view returns (bool) { return markets[address(cToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param cTokens The list of addresses of the cToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory cTokens) public returns (uint[] memory) { uint len = cTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { CToken cToken = CToken(cTokens[i]); results[i] = uint(addToMarketInternal(cToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param cToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(cToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } if (accountAssets[borrower].length >= maxAssets) { // no space, cannot join return Error.TOO_MANY_ASSETS; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(cToken); emit MarketEntered(cToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param cTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address cTokenAddress) external returns (uint) { CToken cToken = CToken(cTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the cToken */ (uint oErr, uint tokensHeld, uint amountOwed,) = cToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(cToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set cToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete cToken from the account’s list of assets */ // load into memory for faster iteration CToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == cToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 CToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.length--; emit MarketExited(cToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param cToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[cToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, minter, false); return uint(Error.NO_ERROR); } /** * @notice Validates mint and reverts on rejection. May emit logs. * @param cToken Asset being minted * @param minter The address minting the tokens * @param actualMintAmount The amount of the underlying asset being minted * @param mintTokens The number of tokens being minted */ function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external { // Shh - currently unused cToken; minter; actualMintAmount; mintTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param cToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint) { uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, redeemer, false); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[cToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param cToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external { // Shh - currently unused cToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param cToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[cToken], "borrow is paused"); if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[cToken].accountMembership[borrower]) { // only cTokens may call borrowAllowed if borrower not in market require(msg.sender == cToken, "sender must be cToken"); // attempt to add borrower to the market Error err = addToMarketInternal(CToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[cToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) { return uint(Error.PRICE_ERROR); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa : CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates borrow and reverts on rejection. May emit logs. * @param cToken Asset whose underlying is being borrowed * @param borrower The address borrowing the underlying * @param borrowAmount The amount of the underlying asset requested to borrow */ function borrowVerify(address cToken, address borrower, uint borrowAmount) external { // Shh - currently unused cToken; borrower; borrowAmount; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param cToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[cToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa : CToken(cToken).borrowIndex()}); updateCompBorrowIndex(cToken, borrowIndex); distributeBorrowerComp(cToken, borrower, borrowIndex, false); return uint(Error.NO_ERROR); } /** * @notice Validates repayBorrow and reverts on rejection. May emit logs. * @param cToken Asset being repaid * @param payer The address repaying the borrow * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function repayBorrowVerify( address cToken, address payer, address borrower, uint actualRepayAmount, uint borrowerIndex) external { // Shh - currently unused cToken; payer; borrower; actualRepayAmount; borrowerIndex; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the liquidation should be allowed to occur * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint) { // Shh - currently unused liquidator; if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower); (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa : closeFactorMantissa}), borrowBalance); if (mathErr != MathError.NO_ERROR) { return uint(Error.MATH_ERROR); } if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Validates liquidateBorrow and reverts on rejection. May emit logs. * @param cTokenBorrowed Asset which was borrowed by the borrower * @param cTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param actualRepayAmount The amount of underlying being repaid */ function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint actualRepayAmount, uint seizeTokens) external { // Shh - currently unused cTokenBorrowed; cTokenCollateral; liquidator; borrower; actualRepayAmount; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the seizing of assets should be allowed to occur * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) { return uint(Error.COMPTROLLER_MISMATCH); } // Keep the flywheel moving updateCompSupplyIndex(cTokenCollateral); distributeSupplierComp(cTokenCollateral, borrower, false); distributeSupplierComp(cTokenCollateral, liquidator, false); return uint(Error.NO_ERROR); } /** * @notice Validates seize and reverts on rejection. May emit logs. * @param cTokenCollateral Asset which was used as collateral and will be seized * @param cTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external { // Shh - currently unused cTokenCollateral; cTokenBorrowed; liquidator; borrower; seizeTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param cToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(cToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateCompSupplyIndex(cToken); distributeSupplierComp(cToken, src, false); distributeSupplierComp(cToken, dst, false); return uint(Error.NO_ERROR); } /** * @notice Validates transfer and reverts on rejection. May emit logs. * @param cToken Asset being transferred * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of cTokens to transfer */ function transferVerify(address cToken, address src, address dst, uint transferTokens) external { // Shh - currently unused cToken; src; dst; transferTokens; // Shh - we don't ever want this hook to be marked pure if (false) { maxAssets = maxAssets; } } /*** Liquidity/Liquidation Calculations ***/ /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `cTokenBalance` is the number of cTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint cTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; Exp collateralFactor; Exp exchangeRate; Exp oraclePrice; Exp tokensToDenom; } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address cTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param cTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, CToken cTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; MathError mErr; // For each asset the account is in CToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { CToken asset = assets[i]; // Read the balances and exchange rate from the cToken (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account); if (oErr != 0) {// semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa : markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa : vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = Exp({mantissa : vars.oraclePriceMantissa}); // Pre-compute a conversion factor from tokens -> ether (normalized price value) (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumCollateral += tokensToDenom * cTokenBalance (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // sumBorrowPlusEffects += oraclePrice * borrowBalance (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // Calculate effects of interacting with cTokenModify if (asset == cTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); if (mErr != MathError.NO_ERROR) { return (Error.MATH_ERROR, 0, 0); } } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Calculate number of tokens of collateral asset to seize given an underlying amount * @dev Used in liquidation (called in cToken.liquidateBorrowFresh) * @param cTokenBorrowed The address of the borrowed cToken * @param cTokenCollateral The address of the collateral cToken * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation) */ function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) { /* Read oracle prices for borrowed and collateral markets */ uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed)); uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral)); if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) { return (uint(Error.PRICE_ERROR), 0); } /* * Get the exchange rate and calculate the number of collateral tokens to seize: * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral * seizeTokens = seizeAmount / exchangeRate * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate) */ uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error uint seizeTokens; Exp memory numerator; Exp memory denominator; Exp memory ratio; MathError mathErr; (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, ratio) = divExp(numerator, denominator); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount); if (mathErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0); } return (uint(Error.NO_ERROR), seizeTokens); } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the comptroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the comptroller PriceOracle oldOracle = oracle; // Set comptroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK); } Exp memory newCloseFactorExp = Exp({mantissa : newCloseFactorMantissa}); Exp memory lowLimit = Exp({mantissa : closeFactorMinMantissa}); if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } Exp memory highLimit = Exp({mantissa : closeFactorMaxMantissa}); if (lessThanExp(highLimit, newCloseFactorExp)) { return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION); } uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param cToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(cToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } Exp memory newCollateralFactorExp = Exp({mantissa : newCollateralFactorMantissa}); // Check collateral factor <= 0.9 Exp memory highLimit = Exp({mantissa : collateralFactorMaxMantissa}); if (lessThanExp(highLimit, newCollateralFactorExp)) { return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets maxAssets which controls how many markets can be entered * @dev Admin function to set maxAssets * @param newMaxAssets New max assets * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setMaxAssets(uint newMaxAssets) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK); } uint oldMaxAssets = maxAssets; maxAssets = newMaxAssets; emit NewMaxAssets(oldMaxAssets, newMaxAssets); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Check de-scaled min <= newLiquidationIncentive <= max Exp memory newLiquidationIncentive = Exp({mantissa : newLiquidationIncentiveMantissa}); Exp memory minLiquidationIncentive = Exp({mantissa : liquidationIncentiveMinMantissa}); if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } Exp memory maxLiquidationIncentive = Exp({mantissa : liquidationIncentiveMaxMantissa}); if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) { return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param cToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(CToken cToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(cToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } cToken.isCToken(); // Sanity check to make sure its really a CToken markets[address(cToken)] = Market({isListed : true, isComped : true, collateralFactorMantissa : 0}); _addMarketInternal(address(cToken)); borrowGuardianPaused[address(cToken)] = true; //stage 1, not allow borrow emit MarketListed(cToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address cToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != CToken(cToken), "market already added"); } allMarkets.push(CToken(cToken)); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(cToken)] = state; emit MarketActionPaused(cToken, "Mint", state); return state; } function _setBorrowPaused(CToken cToken, bool state) public returns (bool) { require(markets[address(cToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(cToken)] = state; emit MarketActionPaused(cToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } function _become(Unitroller unitroller) public { require(msg.sender == unitroller.admin(), "only unitroller admin can change brains"); require(unitroller._acceptImplementation() == 0, "change not authorized"); } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == comptrollerImplementation; } /*** Comp Distribution ***/ /** * @notice Recalculate and update COMP speeds for all COMP markets */ function refreshCompSpeeds() public { require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds"); refreshCompSpeedsInternal(); } function refreshCompSpeedsInternal() internal { CToken[] memory allMarkets_ = allMarkets; for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; Exp memory borrowIndex = Exp({mantissa : cToken.borrowIndex()}); updateCompSupplyIndex(address(cToken)); updateCompBorrowIndex(address(cToken), borrowIndex); } Exp memory borrowTotalUtility = Exp({mantissa : 0}); uint borrowAssetCount = 0; Exp memory borrowAverageUtility = Exp({mantissa : 0}); //calculate Borrow asset totalUtility if (miningRule == 1) {//mining by borrow for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped && !borrowGuardianPaused[address(cToken)]) { Exp memory assetPrice = Exp({mantissa : oracle.getUnderlyingPriceWithoutScale(cToken)}); Exp memory utility = mul_(assetPrice, cToken.totalBorrows()); borrowTotalUtility = add_(borrowTotalUtility, utility); borrowAssetCount++; } } if (borrowAssetCount > 0) { borrowAverageUtility = div_(borrowTotalUtility, borrowAssetCount); } } Exp memory totalUtility = Exp({mantissa : 0}); Exp[] memory utilities = new Exp[](allMarkets_.length); for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets_[i]; if (markets[address(cToken)].isComped) { uint buff = miningBuff[address(cToken)]; if (buff == 0) buff = 1; Exp memory price = Exp({mantissa : oracle.getUnderlyingPriceWithoutScale(cToken)}); if (miningRule == 0) {//mining by supply Exp memory realUtility = mul_(price, cToken.totalSupply()); Exp memory utility = mul_(realUtility, buff); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } else if (miningRule == 1) {//mining by borrow if (borrowGuardianPaused[address(cToken)]) { Exp memory utility = mul_(borrowAverageUtility, buff); //averageUtility with in price utilities[i] = utility; totalUtility = add_(totalUtility, utility); } else { Exp memory realUtility = mul_(price, cToken.totalBorrows()); Exp memory utility = mul_(realUtility, buff); utilities[i] = utility; totalUtility = add_(totalUtility, utility); } } else {//can't support revert(); } } } for (uint i = 0; i < allMarkets_.length; i++) { CToken cToken = allMarkets[i]; uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0; compSpeeds[address(cToken)] = newSpeed; emit CompSpeedUpdated(cToken, newSpeed, totalUtility.mantissa, utilities[i].mantissa); } } /** * @notice Accrue COMP to the market by updating the supply index * @param cToken The market whose supply index to update */ function updateCompSupplyIndex(address cToken) internal { CompMarketState storage supplyState = compSupplyState[cToken]; uint supplySpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = CToken(cToken).totalSupply(); uint compAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa : 0}); Double memory index = add_(Double({mantissa : supplyState.index}), ratio); compSupplyState[cToken] = CompMarketState({ index : safe224(index.mantissa, "new index exceeds 224 bits"), block : safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue COMP to the market by updating the borrow index * @param cToken The market whose borrow index to update */ function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal { CompMarketState storage borrowState = compBorrowState[cToken]; uint borrowSpeed = compSpeeds[cToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex); uint compAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa : 0}); Double memory index = add_(Double({mantissa : borrowState.index}), ratio); compBorrowState[cToken] = CompMarketState({ index : safe224(index.mantissa, "new index exceeds 224 bits"), block : safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate COMP accrued by a supplier and possibly transfer it to them * @param cToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute COMP to */ function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal { CompMarketState storage supplyState = compSupplyState[cToken]; Double memory supplyIndex = Double({mantissa : supplyState.index}); Double memory supplierIndex = Double({mantissa : compSupplierIndex[cToken][supplier]}); compSupplierIndex[cToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CToken(cToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(compAccrued[supplier], supplierDelta); compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate COMP accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param cToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute COMP to */ function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal { CompMarketState storage borrowState = compBorrowState[cToken]; Double memory borrowIndex = Double({mantissa : borrowState.index}); Double memory borrowerIndex = Double({mantissa : compBorrowerIndex[cToken][borrower]}); compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta); compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold); emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Transfer COMP to the user, if they are above the threshold * @dev Note: If there is not enough COMP, we do not perform the transfer all. * @param user The address of the user to transfer COMP to * @param userAccrued The amount of COMP to (possibly) transfer * @return The amount of COMP which was NOT transferred to the user */ function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) { if (userAccrued >= threshold && userAccrued > 0) { Cheese cheese = Cheese(getCheeseAddress()); uint cheeseRemaining = cheese.balanceOf(address(this)); if (userAccrued <= cheeseRemaining) { cheese.transfer(user, userAccrued); return 0; } } return userAccrued; } /** * @notice Claim all the comp accrued by holder in all markets * @param holder The address to claim COMP for */ function claimComp(address holder) public { return claimComp(holder, allMarkets); } /** * @notice Claim all the comp accrued by holder in the specified markets * @param holder The address to claim COMP for * @param cTokens The list of markets to claim COMP in */ function claimComp(address holder, CToken[] memory cTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimComp(holders, cTokens, true, true); } /** * @notice Claim all comp accrued by the holders * @param holders The addresses to claim COMP for * @param cTokens The list of markets to claim COMP in * @param borrowers Whether or not to claim COMP earned by borrowing * @param suppliers Whether or not to claim COMP earned by supplying */ function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public { for (uint i = 0; i < cTokens.length; i++) { CToken cToken = cTokens[i]; require(markets[address(cToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa : cToken.borrowIndex()}); updateCompBorrowIndex(address(cToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true); } } if (suppliers == true) { updateCompSupplyIndex(address(cToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierComp(address(cToken), holders[j], true); } } } } /*** Comp Distribution Admin ***/ /** * @notice Set the amount of COMP distributed per block * @param compRate_ The amount of COMP wei per block to distribute */ function _setCompRate(uint compRate_) public { require(adminOrInitializing(), "only admin can change comp rate"); uint oldRate = compRate; compRate = compRate_; emit NewCompRate(oldRate, compRate_); refreshCompSpeedsInternal(); } /** * @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel * @param cTokens The addresses of the markets to add */ function _addCompMarkets(address[] memory cTokens) public { require(adminOrInitializing(), "only admin can add comp market"); for (uint i = 0; i < cTokens.length; i++) { _addCompMarketInternal(cTokens[i]); } refreshCompSpeedsInternal(); } function _addCompMarketInternal(address cToken) internal { Market storage market = markets[cToken]; require(market.isListed == true, "comp market is not listed"); require(market.isComped == false, "comp market already added"); market.isComped = true; emit MarketComped(CToken(cToken), true); if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) { compSupplyState[cToken] = CompMarketState({ index : compInitialIndex, block : safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) { compBorrowState[cToken] = CompMarketState({ index : compInitialIndex, block : safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } /** * @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel * @param cToken The address of the market to drop */ function _dropCompMarket(address cToken) public { require(msg.sender == admin, "only admin can drop comp market"); Market storage market = markets[cToken]; require(market.isComped == true, "market is not a comp market"); market.isComped = false; emit MarketComped(CToken(cToken), false); refreshCompSpeedsInternal(); } function _setMiningBuff(address cToken, uint buff) public { require(adminOrInitializing(), "only admin can change cheese rate"); miningBuff[cToken] = buff; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (CToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the COMP token * @return The address of COMP */ function getCheeseAddress() public view returns (address) { return 0x88C97F3fC11E28650F10c1862381A3262B572270; } } contract CErc20 is CToken, CErc20Interface { constructor() public { admin = msg.sender; } /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // CToken initialize does the bulk of the work super.initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param cTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral); return err; } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal returns (uint) { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this)); token.transferFrom(from, address(this), amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a compliant ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_IN_FAILED"); // Calculate the amount that was *actually* transferred uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal { EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying); token.transfer(to, amount); bool success; assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 success := not(0) // set success to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) success := mload(0) // Set `success = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } require(success, "TOKEN_TRANSFER_OUT_FAILED"); } } contract CErc20Delegate is CErc20, CDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == admin, "only the admin may call _resignImplementation"); } } contract CErc20Immutable is CErc20 { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; // Initialize the market initialize(underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } } contract CEther is CToken { /** * @notice Construct a new CEther money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token */ constructor(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_) public { // Creator of the contract is admin during initialization admin = msg.sender; initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set the proper admin now that initialization is done admin = admin_; } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Reverts upon any failure */ function mint() external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { return borrowInternal(borrowAmount); } /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable { (uint err,) = repayBorrowInternal(msg.value); requireNoError(err, "repayBorrow failed"); } /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable { (uint err,) = repayBorrowBehalfInternal(borrower, msg.value); requireNoError(err, "repayBorrowBehalf failed"); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable { (uint err,) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral); requireNoError(err, "liquidateBorrow failed"); } /** * @notice Send Ether to CEther to mint */ function () external payable { (uint err,) = mintInternal(msg.value); requireNoError(err, "mint failed"); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of Ether, before this message * @dev This excludes the value of the current message, if any * @return The quantity of Ether owned by this contract */ function getCashPrior() internal view returns (uint) { (MathError err, uint startingBalance) = subUInt(address(this).balance, msg.value); require(err == MathError.NO_ERROR); return startingBalance; } /** * @notice Perform the actual transfer in, which is a no-op * @param from Address sending the Ether * @param amount Amount of Ether being sent * @return The actual amount of Ether transferred */ function doTransferIn(address from, uint amount) internal returns (uint) { // Sanity checks require(msg.sender == from, "sender mismatch"); require(msg.value == amount, "value mismatch"); return amount; } function doTransferOut(address payable to, uint amount) internal { /* Send the Ether, with minimal gas and revert on failure */ to.transfer(amount); } function requireNoError(uint errCode, string memory message) internal pure { if (errCode == uint(Error.NO_ERROR)) { return; } bytes memory fullMessage = new bytes(bytes(message).length + 5); uint i; for (i = 0; i < bytes(message).length; i++) { fullMessage[i] = bytes(message)[i]; } fullMessage[i+0] = byte(uint8(32)); fullMessage[i+1] = byte(uint8(40)); fullMessage[i+2] = byte(uint8(48 + ( errCode / 10 ))); fullMessage[i+3] = byte(uint8(48 + ( errCode % 10 ))); fullMessage[i+4] = byte(uint8(41)); require(errCode == uint(Error.NO_ERROR), string(fullMessage)); } } contract CDaiDelegate is CErc20Delegate { /** * @notice DAI adapter address */ address public daiJoinAddress; /** * @notice DAI Savings Rate (DSR) pot address */ address public potAddress; /** * @notice DAI vat address */ address public vatAddress; /** * @notice Delegate interface to become the implementation * @param data The encoded arguments for becoming */ function _becomeImplementation(bytes memory data) public { require(msg.sender == admin, "only the admin may initialize the implementation"); (address daiJoinAddress_, address potAddress_) = abi.decode(data, (address, address)); return _becomeImplementation(daiJoinAddress_, potAddress_); } /** * @notice Explicit interface to become the implementation * @param daiJoinAddress_ DAI adapter address * @param potAddress_ DAI Savings Rate (DSR) pot address */ function _becomeImplementation(address daiJoinAddress_, address potAddress_) internal { // Get dai and vat and sanity check the underlying DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress_); PotLike pot = PotLike(potAddress_); GemLike dai = daiJoin.dai(); VatLike vat = daiJoin.vat(); require(address(dai) == underlying, "DAI must be the same as underlying"); // Remember the relevant addresses daiJoinAddress = daiJoinAddress_; potAddress = potAddress_; vatAddress = address(vat); // Approve moving our DAI into the vat through daiJoin dai.approve(daiJoinAddress, uint(-1)); // Approve the pot to transfer our funds within the vat vat.hope(potAddress); vat.hope(daiJoinAddress); // Accumulate DSR interest -- must do this in order to doTransferIn pot.drip(); // Transfer all cash in (doTransferIn does this regardless of amount) doTransferIn(address(this), 0); } /** * @notice Delegate interface to resign the implementation */ function _resignImplementation() public { require(msg.sender == admin, "only the admin may abandon the implementation"); // Transfer all cash out of the DSR - note that this relies on self-transfer DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); PotLike pot = PotLike(potAddress); VatLike vat = VatLike(vatAddress); // Accumulate interest pot.drip(); // Calculate the total amount in the pot, and move it out uint pie = pot.pie(address(this)); pot.exit(pie); // Checks the actual balance of DAI in the vat after the pot exit uint bal = vat.dai(address(this)); // Remove our whole balance daiJoin.exit(address(this), bal / RAY); } /*** CToken Overrides ***/ /** * @notice Accrues DSR then applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { // Accumulate DSR interest PotLike(potAddress).drip(); // Accumulate CToken interest return super.accrueInterest(); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal view returns (uint) { PotLike pot = PotLike(potAddress); uint pie = pot.pie(address(this)); return mul(pot.chi(), pie) / RAY; } /** * @notice Transfer the underlying to this contract and sweep into DSR pot * @param from Address to transfer funds from * @param amount Amount of underlying to transfer * @return The actual amount that is transferred */ function doTransferIn(address from, uint amount) internal returns (uint) { // Perform the EIP-20 transfer in EIP20Interface token = EIP20Interface(underlying); require(token.transferFrom(from, address(this), amount), "unexpected EIP-20 transfer in return"); DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); GemLike dai = GemLike(underlying); PotLike pot = PotLike(potAddress); VatLike vat = VatLike(vatAddress); // Convert all our DAI to internal DAI in the vat daiJoin.join(address(this), dai.balanceOf(address(this))); // Checks the actual balance of DAI in the vat after the join uint bal = vat.dai(address(this)); // Calculate the percentage increase to th pot for the entire vat, and move it in // Note: We may leave a tiny bit of DAI in the vat...but we do the whole thing every time uint pie = bal / pot.chi(); pot.join(pie); return amount; } /** * @notice Transfer the underlying from this contract, after sweeping out of DSR pot * @param to Address to transfer funds to * @param amount Amount of underlying to transfer */ function doTransferOut(address payable to, uint amount) internal { DaiJoinLike daiJoin = DaiJoinLike(daiJoinAddress); PotLike pot = PotLike(potAddress); // Calculate the percentage decrease from the pot, and move that much out // Note: Use a slightly larger pie size to ensure that we get at least amount in the vat uint pie = add(mul(amount, RAY) / pot.chi(), 1); pot.exit(pie); daiJoin.exit(to, amount); } /*** Maker Internals ***/ uint256 constant RAY = 10 ** 27; function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "add-overflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } }
0x608060405234801561001057600080fd5b506004361061043d5760003560e01c8063731f0c2b11610236578063bb82aa5e1161013b578063da3d454c116100c3578063e875544611610087578063e875544614611145578063e9af02921461114d578063eabe7d9114611173578063ede4edd0146111a9578063f851a440146111cf5761043d565b8063da3d454c146110a7578063dce15449146110dd578063dcfbc0c714611109578063e4028eee14611111578063e6653f3d1461113d5761043d565b8063ca0af0431161010a578063ca0af04314610f4f578063cc7ebdc414610f7d578063ce485c5e14610fa3578063d02f735114611044578063d9226ced1461108a5761043d565b8063bb82aa5e14610e1b578063bdcdc25814610e23578063c299823814610e5f578063c488847b14610f005761043d565b806394b2294b116101be578063aa9007541161018d578063aa90075414610d5f578063abfceffc14610d67578063ac0b0bb714610ddd578063b0772d0b14610de5578063b21be7fd14610ded5761043d565b806394b2294b14610ce1578063a0cb34c914610ce9578063a76b3fda14610d15578063a7f0e23114610d3b5761043d565b806387f763031161020557806387f7630314610c1e5780638c57804e14610c265780638e8f294b14610c4c5780638ebf636414610c94578063929fe9a114610cb35761043d565b8063731f0c2b14610be0578063747026c914610c065780637dc0d1d014610c0e57806385d43cbf14610c165761043d565b806347ef3b3b116103475780635c778605116102cf5780636a491112116102935780636a49111214610acd5780636a56947e14610aea5780636b79c38d14610b265780636d154ea514610b745780636d35bf9114610b9a5761043d565b80635c778605146108d95780635ec88c791461090f5780635f5af1aa146109355780635fc7e71e1461095b5780636810dfa6146109a15761043d565b80634ef4c3e1116103165780634ef4c3e1146108075780634fd42e171461083d57806351dff9891461085a57806352d84d1e1461089657806355ee1fe1146108b35761043d565b806347ef3b3b146107515780634ada90af1461079d5780634d8e5037146107a55780634e79238f146107ad5761043d565b806326782247116103ca5780633bcf7ec1116103995780633bcf7ec1146106cf5780633c94786f146106fd5780634110db981461070557806341c728b91461070d57806342cbb15c146107495761043d565b806326782247146106655780632d70db781461066d578063317b0b771461068c5780633aa729b4146106a95761043d565b80631d504dc6116104115780631d504dc6146105775780631d7b33d71461059d5780631ededc91146105c357806324008a621461060557806324a3d622146106415761043d565b80627e3dd2146104425780630d2f60af1461045e57806318c882a5146104965780631c3db2e0146104c4575b600080fd5b61044a6111d7565b604080519115158252519081900360200190f35b6104846004803603602081101561047457600080fd5b50356001600160a01b03166111dc565b60408051918252519081900360200190f35b61044a600480360360408110156104ac57600080fd5b506001600160a01b03813516906020013515156111ee565b610575600480360360408110156104da57600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561050457600080fd5b82018360208201111561051657600080fd5b803590602001918460208302840111600160201b8311171561053757600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061138e945050505050565b005b6105756004803603602081101561058d57600080fd5b50356001600160a01b03166113f0565b610484600480360360208110156105b357600080fd5b50356001600160a01b031661154f565b610575600480360360a08110156105d957600080fd5b506001600160a01b03813581169160208101358216916040820135169060608101359060800135611561565b6104846004803603608081101561061b57600080fd5b506001600160a01b03813581169160208101358216916040820135169060600135611568565b610649611631565b604080516001600160a01b039092168252519081900360200190f35b610649611640565b61044a6004803603602081101561068357600080fd5b5035151561164f565b610484600480360360208110156106a257600080fd5b5035611789565b610575600480360360208110156106bf57600080fd5b50356001600160a01b031661189a565b61044a600480360360408110156106e557600080fd5b506001600160a01b03813516906020013515156119cb565b61044a611b66565b610484611b76565b6105756004803603608081101561072357600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611b7c565b610484611b82565b610575600480360360c081101561076757600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060808101359060a00135611b87565b610484611b8f565b610575611b95565b6107e9600480360360808110156107c357600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611bdd565b60408051938452602084019290925282820152519081900360600190f35b6104846004803603606081101561081d57600080fd5b506001600160a01b03813581169160208101359091169060400135611c17565b6104846004803603602081101561085357600080fd5b5035611cc2565b6105756004803603608081101561087057600080fd5b506001600160a01b03813581169160208101359091169060408101359060600135611db6565b610649600480360360208110156108ac57600080fd5b5035611e0a565b610484600480360360208110156108c957600080fd5b50356001600160a01b0316611e31565b610575600480360360608110156108ef57600080fd5b506001600160a01b03813581169160208101359091169060400135611eb8565b6107e96004803603602081101561092557600080fd5b50356001600160a01b0316611ebd565b6104846004803603602081101561094b57600080fd5b50356001600160a01b0316611ef2565b610484600480360360a081101561097157600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135611f76565b610575600480360360808110156109b757600080fd5b810190602081018135600160201b8111156109d157600080fd5b8201836020820111156109e357600080fd5b803590602001918460208302840111600160201b83111715610a0457600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295949360208101935035915050600160201b811115610a5357600080fd5b820183602082011115610a6557600080fd5b803590602001918460208302840111600160201b83111715610a8657600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295505050508035151591506020013515156120fd565b61057560048036036020811015610ae357600080fd5b50356122a6565b61057560048036036080811015610b0057600080fd5b506001600160a01b03813581169160208101358216916040820135169060600135611b7c565b610b4c60048036036020811015610b3c57600080fd5b50356001600160a01b031661234a565b604080516001600160e01b03909316835263ffffffff90911660208301528051918290030190f35b61044a60048036036020811015610b8a57600080fd5b50356001600160a01b0316612374565b610575600480360360a0811015610bb057600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135611561565b61044a60048036036020811015610bf657600080fd5b50356001600160a01b0316612389565b61048461239e565b6106496123aa565b6106496123b9565b61044a6123d1565b610b4c60048036036020811015610c3c57600080fd5b50356001600160a01b03166123e1565b610c7260048036036020811015610c6257600080fd5b50356001600160a01b031661240b565b6040805193151584526020840192909252151582820152519081900360600190f35b61044a60048036036020811015610caa57600080fd5b50351515612431565b61044a60048036036040811015610cc957600080fd5b506001600160a01b038135811691602001351661256a565b61048461259d565b61057560048036036040811015610cff57600080fd5b506001600160a01b0381351690602001356125a3565b61048460048036036020811015610d2b57600080fd5b50356001600160a01b0316612602565b610d4361277b565b604080516001600160e01b039092168252519081900360200190f35b61048461278e565b610d8d60048036036020811015610d7d57600080fd5b50356001600160a01b0316612794565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610dc9578181015183820152602001610db1565b505050509050019250505060405180910390f35b61044a61281d565b610d8d61282d565b61048460048036036040811015610e0357600080fd5b506001600160a01b038135811691602001351661288f565b6106496128ac565b61048460048036036080811015610e3957600080fd5b506001600160a01b038135811691602081013582169160408201351690606001356128bb565b610d8d60048036036020811015610e7557600080fd5b810190602081018135600160201b811115610e8f57600080fd5b820183602082011115610ea157600080fd5b803590602001918460208302840111600160201b83111715610ec257600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061294f945050505050565b610f3660048036036060811015610f1657600080fd5b506001600160a01b038135811691602081013590911690604001356129e6565b6040805192835260208301919091528051918290030190f35b61048460048036036040811015610f6557600080fd5b506001600160a01b0381358116916020013516612c5b565b61048460048036036020811015610f9357600080fd5b50356001600160a01b0316612c78565b61057560048036036020811015610fb957600080fd5b810190602081018135600160201b811115610fd357600080fd5b820183602082011115610fe557600080fd5b803590602001918460208302840111600160201b8311171561100657600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612c8a945050505050565b610484600480360360a081101561105a57600080fd5b506001600160a01b0381358116916020810135821691604082013581169160608101359091169060800135612d1c565b610484600480360360208110156110a057600080fd5b5035612ed4565b610484600480360360608110156110bd57600080fd5b506001600160a01b03813581169160208101359091169060400135612f3d565b610649600480360360408110156110f357600080fd5b506001600160a01b03813516906020013561322a565b61064961325f565b6104846004803603604081101561112757600080fd5b506001600160a01b03813516906020013561326e565b61044a61341e565b61048461342e565b6105756004803603602081101561116357600080fd5b50356001600160a01b0316613434565b6104846004803603606081101561118957600080fd5b506001600160a01b03813581169160208101359091169060400135613498565b610484600480360360208110156111bf57600080fd5b50356001600160a01b03166134d5565b6106496137e8565b600181565b60166020526000908152604090205481565b6001600160a01b03821660009081526009602052604081205460ff166112455760405162461bcd60e51b8152600401808060200182810382526028815260200180615d316028913960400191505060405180910390fd5b600a546001600160a01b031633148061126857506000546001600160a01b031633145b6112a35760405162461bcd60e51b8152600401808060200182810382526027815260200180615dab6027913960400191505060405180910390fd5b6000546001600160a01b03163314806112be57506001821515145b611308576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b6001600160a01b0383166000818152600c6020908152604091829020805486151560ff199091168117909155825193845283830152606090830181905260069083015265426f72726f7760d01b6080830152517f4ab2c577b7459254dd330a38beef1d66ae70ba1ab28db7147d52d3a752a03cdc9181900360a00190a150805b92915050565b6040805160018082528183019092526060916020808301908038833901905050905082816000815181106113be57fe5b60200260200101906001600160a01b031690816001600160a01b0316815250506113eb81836001806120fd565b505050565b806001600160a01b031663f851a4406040518163ffffffff1660e01b815260040160206040518083038186803b15801561142957600080fd5b505afa15801561143d573d6000803e3d6000fd5b505050506040513d602081101561145357600080fd5b50516001600160a01b0316331461149b5760405162461bcd60e51b8152600401808060200182810382526027815260200180615e176027913960400191505060405180910390fd5b806001600160a01b031663c1e803346040518163ffffffff1660e01b8152600401602060405180830381600087803b1580156114d657600080fd5b505af11580156114ea573d6000803e3d6000fd5b505050506040513d602081101561150057600080fd5b50511561154c576040805162461bcd60e51b815260206004820152601560248201527418da185b99d9481b9bdd08185d5d1a1bdc9a5e9959605a1b604482015290519081900360640190fd5b50565b600f6020526000908152604090205481565b5050505050565b6001600160a01b03841660009081526009602052604081205460ff1661159057506009611629565b611598615c71565b6040518060200160405280876001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156115dc57600080fd5b505afa1580156115f0573d6000803e3d6000fd5b505050506040513d602081101561160657600080fd5b50519052905061161686826137f7565b6116238685836000613a7f565b60009150505b949350505050565b600a546001600160a01b031681565b6001546001600160a01b031681565b600a546000906001600160a01b031633148061167557506000546001600160a01b031633145b6116b05760405162461bcd60e51b8152600401808060200182810382526027815260200180615dab6027913960400191505060405180910390fd5b6000546001600160a01b03163314806116cb57506001821515145b611715576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b600a8054831515600160b81b810260ff60b81b1990921691909117909155604080516020810192909252808252600582820152645365697a6560d81b6060830152517fef159d9a32b2472e32b098f954f3ce62d232939f1c207070b584df1814de2de09181900360800190a150805b919050565b600080546001600160a01b031633146117af576117a860016004613c6b565b9050611784565b6117b7615c71565b5060408051602081019091528281526117ce615c71565b50604080516020810190915266b1a2bc2ec5000081526117ee8282613cd1565b15611807576117fe600580613c6b565b92505050611784565b61180f615c71565b506040805160208101909152670c7d713b49da000081526118308184613cd9565b1561184a57611840600580613c6b565b9350505050611784565b6005805490869055604080518281526020810188905281517f3b9670cf975d26958e754b57098eaa2ac914d8d2a31b83257997b9f346110fd9929181900390910190a160005b9695505050505050565b6000546001600160a01b031633146118f9576040805162461bcd60e51b815260206004820152601f60248201527f6f6e6c792061646d696e2063616e2064726f7020636f6d70206d61726b657400604482015290519081900360640190fd5b6001600160a01b0381166000908152600960205260409020600381015460ff16151560011461196f576040805162461bcd60e51b815260206004820152601b60248201527f6d61726b6574206973206e6f74206120636f6d70206d61726b65740000000000604482015290519081900360640190fd5b60038101805460ff19169055604080516001600160a01b03841681526000602082015281517f93c1f3e36ed71139f466a4ce8c9751790e2e33f5afb2df0dcfb3aeabe55d5aa2929181900390910190a16119c7613ce0565b5050565b6001600160a01b03821660009081526009602052604081205460ff16611a225760405162461bcd60e51b8152600401808060200182810382526028815260200180615d316028913960400191505060405180910390fd5b600a546001600160a01b0316331480611a4557506000546001600160a01b031633145b611a805760405162461bcd60e51b8152600401808060200182810382526027815260200180615dab6027913960400191505060405180910390fd5b6000546001600160a01b0316331480611a9b57506001821515145b611ae5576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b6001600160a01b0383166000818152600b6020908152604091829020805486151560ff199091168117909155825193845283830152606090830181905260049083015263135a5b9d60e21b6080830152517f4ab2c577b7459254dd330a38beef1d66ae70ba1ab28db7147d52d3a752a03cdc9181900360a00190a150919050565b600a54600160a01b900460ff1681565b60105481565b50505050565b435b90565b505050505050565b60065481565b333214611bd35760405162461bcd60e51b8152600401808060200182810382526031815260200180615d7a6031913960400191505060405180910390fd5b611bdb613ce0565b565b600080600080600080611bf28a8a8a8a61437b565b925092509250826011811115611c0457fe5b95509093509150505b9450945094915050565b6001600160a01b0383166000908152600b602052604081205460ff1615611c76576040805162461bcd60e51b815260206004820152600e60248201526d1b5a5b9d081a5cc81c185d5cd95960921b604482015290519081900360640190fd5b6001600160a01b03841660009081526009602052604090205460ff16611ca05760095b9050611cbb565b611ca984614796565b611cb584846000614a14565b60005b90505b9392505050565b600080546001600160a01b03163314611ce1576117a86001600b613c6b565b611ce9615c71565b506040805160208101909152828152611d00615c71565b506040805160208101909152670de0b6b3a76400008152611d218282613cd9565b15611d32576117fe6007600c613c6b565b611d3a615c71565b5060408051602081019091526714d1120d7b1600008152611d5b8184613cd9565b15611d6c576118406007600c613c6b565b6006805490869055604080518281526020810188905281517faeba5a6c40a8ac138134bff1aaa65debf25971188a58804bad717f82f0ec1316929181900390910190a16000611890565b80158015611dc45750600082115b15611b7c576040805162461bcd60e51b815260206004820152601160248201527072656465656d546f6b656e73207a65726f60781b604482015290519081900360640190fd5b600d8181548110611e1757fe5b6000918252602090912001546001600160a01b0316905081565b600080546001600160a01b03163314611e50576117a860016010613c6b565b600480546001600160a01b038481166001600160a01b0319831681179093556040805191909216808252602082019390935281517fd52b2b9b7e9ee655fcb95d2e5b9e0c9f69e7ef2b8e9d2d0ea78402d576d22e22929181900390910190a160009392505050565b6113eb565b600080600080600080611ed487600080600061437b565b925092509250826011811115611ee657fe5b97919650945092505050565b600080546001600160a01b03163314611f11576117a860016013613c6b565b600a80546001600160a01b038481166001600160a01b0319831617928390556040805192821680845293909116602083015280517f0613b6ee6a04f0d09f390e4d9318894b9f6ac7fd83897cd8d18896ba579c401e9281900390910190a16000611cbb565b6001600160a01b03851660009081526009602052604081205460ff161580611fb757506001600160a01b03851660009081526009602052604090205460ff16155b15611fc65760095b90506120f4565b600080611fd285614c0d565b91935090915060009050826011811115611fe857fe5b1461200257816011811115611ff957fe5b925050506120f4565b8061200e576003611ff9565b6000886001600160a01b03166395dd9193876040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561206657600080fd5b505afa15801561207a573d6000803e3d6000fd5b505050506040513d602081101561209057600080fd5b50516040805160208101909152600554815290915060009081906120b49084614c2d565b909250905060008260038111156120c757fe5b146120db57600b5b955050505050506120f4565b808711156120ea5760116120cf565b6000955050505050505b95945050505050565b60005b835181101561156157600084828151811061211757fe5b6020908102919091018101516001600160a01b0381166000908152600990925260409091205490915060ff1661218c576040805162461bcd60e51b81526020600482015260156024820152741b585c9ad95d081b5d5cdd081899481b1a5cdd1959605a1b604482015290519081900360640190fd5b600184151514156122545761219f615c71565b6040518060200160405280836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156121e357600080fd5b505afa1580156121f7573d6000803e3d6000fd5b505050506040513d602081101561220d57600080fd5b50519052905061221d82826137f7565b60005b8751811015612251576122498389838151811061223957fe5b6020026020010151846001613a7f565b600101612220565b50505b6001831515141561229d5761226881614796565b60005b865181101561229b576122938288838151811061228457fe5b60200260200101516001614a14565b60010161226b565b505b50600101612100565b6122ae614c81565b6122ff576040805162461bcd60e51b815260206004820152601f60248201527f6f6e6c792061646d696e2063616e206368616e676520636f6d70207261746500604482015290519081900360640190fd5b600e805490829055604080518281526020810184905281517fc227c9272633c3a307d9845bf2bc2509cefb20d655b5f3c1002d8e1e3f22c8b0929181900390910190a16119c7613ce0565b6011602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b600c6020526000908152604090205460ff1681565b600b6020526000908152604090205460ff1681565b670de0b6b3a764000081565b6004546001600160a01b031681565b7388c97f3fc11e28650f10c1862381a3262b57227090565b600a54600160b01b900460ff1681565b6012602052600090815260409020546001600160e01b03811690600160e01b900463ffffffff1682565b60096020526000908152604090208054600182015460039092015460ff91821692911683565b600a546000906001600160a01b031633148061245757506000546001600160a01b031633145b6124925760405162461bcd60e51b8152600401808060200182810382526027815260200180615dab6027913960400191505060405180910390fd5b6000546001600160a01b03163314806124ad57506001821515145b6124f7576040805162461bcd60e51b81526020600482015260166024820152756f6e6c792061646d696e2063616e20756e706175736560501b604482015290519081900360640190fd5b600a8054831515600160b01b810260ff60b01b1990921691909117909155604080516020810192909252808252600882820152672a3930b739b332b960c11b6060830152517fef159d9a32b2472e32b098f954f3ce62d232939f1c207070b584df1814de2de09181900360800190a15090565b6001600160a01b038082166000908152600960209081526040808320938616835260029093019052205460ff1692915050565b60075481565b6125ab614c81565b6125e65760405162461bcd60e51b8152600401808060200182810382526021815260200180615d596021913960400191505060405180910390fd5b6001600160a01b03909116600090815260166020526040902055565b600080546001600160a01b03163314612621576117a860016012613c6b565b6001600160a01b03821660009081526009602052604090205460ff161561264e576117a8600a6011613c6b565b816001600160a01b031663fe9c44ae6040518163ffffffff1660e01b815260040160206040518083038186803b15801561268757600080fd5b505afa15801561269b573d6000803e3d6000fd5b505050506040513d60208110156126b157600080fd5b5050604080516060810182526001808252600060208381018281528486018481526001600160a01b03891684526009909252949091209251835490151560ff1991821617845593519183019190915551600390910180549115159190921617905561271b82614caa565b6001600160a01b0382166000818152600c6020908152604091829020805460ff19166001179055815192835290517fcf583bb0c569eb967f806b11601c4cb93c10310485c67add5f8362c2f212321f9281900390910190a1600092915050565b6ec097ce7bc90715b34b9f100000000081565b600e5481565b60608060086000846001600160a01b03166001600160a01b0316815260200190815260200160002080548060200260200160405190810160405280929190818152602001828054801561281057602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116127f2575b5093979650505050505050565b600a54600160b81b900460ff1681565b6060600d80548060200260200160405190810160405280929190818152602001828054801561288557602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311612867575b5050505050905090565b601360209081526000928352604080842090915290825290205481565b6002546001600160a01b031681565b600a54600090600160b01b900460ff1615612912576040805162461bcd60e51b81526020600482015260126024820152711d1c985b9cd9995c881a5cc81c185d5cd95960721b604482015290519081900360640190fd5b600061291f868685614d88565b9050801561292e579050611629565b61293786614796565b61294386866000614a14565b61162386856000614a14565b6060600082519050606081604051908082528060200260200182016040528015612983578160200160208202803883390190505b50905060005b828110156129de57600085828151811061299f57fe5b602002602001015190506129b38133614e2b565b60118111156129be57fe5b8383815181106129ca57fe5b602090810291909101015250600101612989565b509392505050565b600480546040805163fc57d4df60e01b81526001600160a01b038781169482019490945290516000938493849391169163fc57d4df91602480820192602092909190829003018186803b158015612a3c57600080fd5b505afa158015612a50573d6000803e3d6000fd5b505050506040513d6020811015612a6657600080fd5b5051600480546040805163fc57d4df60e01b81526001600160a01b038a8116948201949094529051939450600093929091169163fc57d4df91602480820192602092909190829003018186803b158015612abf57600080fd5b505afa158015612ad3573d6000803e3d6000fd5b505050506040513d6020811015612ae957600080fd5b50519050811580612af8575080155b15612b0d57600d935060009250612c53915050565b6000866001600160a01b031663182df0f56040518163ffffffff1660e01b815260040160206040518083038186803b158015612b4857600080fd5b505afa158015612b5c573d6000803e3d6000fd5b505050506040513d6020811015612b7257600080fd5b505190506000612b80615c71565b612b88615c71565b612b90615c71565b6000612b9e60065489614f4c565b945090506000816003811115612bb057fe5b14612bcc57600b5b995060009850612c53975050505050505050565b612bd68787614f4c565b935090506000816003811115612be857fe5b14612bf457600b612bb8565b612bfe8484614f87565b925090506000816003811115612c1057fe5b14612c1c57600b612bb8565b612c26828c614c2d565b955090506000816003811115612c3857fe5b14612c4457600b612bb8565b60009950939750505050505050505b935093915050565b601460209081526000928352604080842090915290825290205481565b60156020526000908152604090205481565b612c92614c81565b612ce3576040805162461bcd60e51b815260206004820152601e60248201527f6f6e6c792061646d696e2063616e2061646420636f6d70206d61726b65740000604482015290519081900360640190fd5b60005b8151811015612d1357612d0b828281518110612cfe57fe5b6020026020010151614f9f565b600101612ce6565b5061154c613ce0565b600a54600090600160b81b900460ff1615612d70576040805162461bcd60e51b815260206004820152600f60248201526e1cd95a5e99481a5cc81c185d5cd959608a1b604482015290519081900360640190fd5b6001600160a01b03861660009081526009602052604090205460ff161580612db157506001600160a01b03851660009081526009602052604090205460ff16155b15612dbd576009611fbf565b846001600160a01b0316635fe3b5676040518163ffffffff1660e01b815260040160206040518083038186803b158015612df657600080fd5b505afa158015612e0a573d6000803e3d6000fd5b505050506040513d6020811015612e2057600080fd5b505160408051635fe3b56760e01b815290516001600160a01b0392831692891691635fe3b567916004808301926020929190829003018186803b158015612e6657600080fd5b505afa158015612e7a573d6000803e3d6000fd5b505050506040513d6020811015612e9057600080fd5b50516001600160a01b031614612ea7576002611fbf565b612eb086614796565b612ebc86846000614a14565b612ec886856000614a14565b60009695505050505050565b600080546001600160a01b03163314612ef3576117a86001600d613c6b565b6007805490839055604080518281526020810185905281517f7093cf1eb653f749c3ff531d6df7f92764536a7fa0d13530cd26e070780c32ea929181900390910190a16000611cbb565b6001600160a01b0383166000908152600c602052604081205460ff1615612f9e576040805162461bcd60e51b815260206004820152601060248201526f189bdc9c9bddc81a5cc81c185d5cd95960821b604482015290519081900360640190fd5b6001600160a01b03841660009081526009602052604090205460ff16612fc5576009611c99565b6001600160a01b038085166000908152600960209081526040808320938716835260029093019052205460ff166130b557336001600160a01b0385161461304b576040805162461bcd60e51b815260206004820152601560248201527439b2b73232b91036bab9ba1031329031aa37b5b2b760591b604482015290519081900360640190fd5b60006130573385614e2b565b9050600081601181111561306757fe5b146130805780601181111561307857fe5b915050611cbb565b6001600160a01b038086166000908152600960209081526040808320938816835260029093019052205460ff166130b357fe5b505b600480546040805163fc57d4df60e01b81526001600160a01b03888116948201949094529051929091169163fc57d4df91602480820192602092909190829003018186803b15801561310657600080fd5b505afa15801561311a573d6000803e3d6000fd5b505050506040513d602081101561313057600080fd5b505161313d57600d611c99565b60008061314d858760008761437b565b9193509091506000905082601181111561316357fe5b1461317d5781601181111561317457fe5b92505050611cbb565b801561318a576004613174565b613192615c71565b6040518060200160405280886001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156131d657600080fd5b505afa1580156131ea573d6000803e3d6000fd5b505050506040513d602081101561320057600080fd5b50519052905061321087826137f7565b61321d8787836000613a7f565b6000979650505050505050565b6008602052816000526040600020818154811061324357fe5b6000918252602090912001546001600160a01b03169150829050565b6003546001600160a01b031681565b600080546001600160a01b031633146132945761328d60016006613c6b565b9050611388565b6001600160a01b0383166000908152600960205260409020805460ff166132c9576132c160096007613c6b565b915050611388565b6132d1615c71565b5060408051602081019091528381526132e8615c71565b506040805160208101909152670c7d713b49da000081526133098183613cd9565b156133245761331a60066008613c6b565b9350505050611388565b84158015906133ad5750600480546040805163fc57d4df60e01b81526001600160a01b038a8116948201949094529051929091169163fc57d4df91602480820192602092909190829003018186803b15801561337f57600080fd5b505afa158015613393573d6000803e3d6000fd5b505050506040513d60208110156133a957600080fd5b5051155b156133be5761331a600d6009613c6b565b60018301805490869055604080516001600160a01b03891681526020810183905280820188905290517f70483e6592cd5182d45ac970e05bc62cdcc90e9d8ef2c2dbe686cf383bcd7fc59181900360600190a16000979650505050505050565b600a54600160a81b900460ff1681565b60055481565b61154c81600d80548060200260200160405190810160405280929190818152602001828054801561348e57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613470575b505050505061138e565b6000806134a6858585614d88565b905080156134b5579050611cbb565b6134be85614796565b6134ca85856000614a14565b600095945050505050565b6000808290506000806000836001600160a01b031663c37f68e2336040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060806040518083038186803b15801561353657600080fd5b505afa15801561354a573d6000803e3d6000fd5b505050506040513d608081101561356057600080fd5b5080516020820151604090920151909450909250905082156135b35760405162461bcd60e51b8152600401808060200182810382526025815260200180615dd26025913960400191505060405180910390fd5b80156135d0576135c5600c6002613c6b565b945050505050611784565b60006135dd873385614d88565b905080156135fe576135f2600e6003836152ba565b95505050505050611784565b6001600160a01b0385166000908152600960209081526040808320338452600281019092529091205460ff1661363d5760009650505050505050611784565b3360009081526002820160209081526040808320805460ff1916905560088252918290208054835181840281018401909452808452606093928301828280156136af57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613691575b5050835193945083925060009150505b8281101561370457896001600160a01b03168482815181106136dd57fe5b60200260200101516001600160a01b031614156136fc57809150613704565b6001016136bf565b5081811061370e57fe5b33600090815260086020526040902080548190600019810190811061372f57fe5b9060005260206000200160009054906101000a90046001600160a01b031681838154811061375957fe5b600091825260209091200180546001600160a01b0319166001600160a01b03929092169190911790558054613792826000198301615c84565b50604080516001600160a01b038c16815233602082015281517fe699a64c18b07ac5b7301aa273f36a2287239eb9501d81950672794afba29a0d929181900390910190a160009c9b505050505050505050505050565b6000546001600160a01b031681565b6001600160a01b0382166000908152601260209081526040808320600f9092528220549091613824611b82565b8354909150600090613844908390600160e01b900463ffffffff16615320565b90506000811180156138565750600083115b15613a255760006138cb876001600160a01b03166347bd37186040518163ffffffff1660e01b815260040160206040518083038186803b15801561389957600080fd5b505afa1580156138ad573d6000803e3d6000fd5b505050506040513d60208110156138c357600080fd5b50518761535a565b905060006138d98386615378565b90506138e3615c71565b60008311613900576040518060200160405280600081525061390a565b61390a82846153ba565b9050613914615c71565b604080516020810190915288546001600160e01b0316815261393690836153f8565b9050604051806040016040528061398683600001516040518060400160405280601a81526020017f6e657720696e646578206578636565647320323234206269747300000000000081525061541d565b6001600160e01b031681526020016139c1886040518060400160405280601c8152602001600080516020615df78339815191528152506154b7565b63ffffffff9081169091526001600160a01b038c166000908152601260209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b0319909416939093171691909117905550611b8792505050565b8015611b8757613a58826040518060400160405280601c8152602001600080516020615df78339815191528152506154b7565b845463ffffffff91909116600160e01b026001600160e01b03909116178455505050505050565b6001600160a01b0384166000908152601260205260409020613a9f615c71565b50604080516020810190915281546001600160e01b03168152613ac0615c71565b5060408051602080820183526001600160a01b03808a16600090815260148352848120918a1680825282845294812080548552865195909152915291909155805115613c6257613b0e615c71565b613b18838361550c565b90506000613ba7896001600160a01b03166395dd91938a6040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015613b7557600080fd5b505afa158015613b89573d6000803e3d6000fd5b505050506040513d6020811015613b9f57600080fd5b50518861535a565b90506000613bb58284615531565b6001600160a01b038a1660009081526015602052604081205491925090613bdc9083615560565b9050613bfe8a828a613bf657670de0b6b3a7640000613bf9565b60005b615596565b6001600160a01b03808c1660008181526015602090815260409182902094909455895181518781529485015280519193928f16927f1fc3ecc087d8d2d15e23d0032af5a47059c3892d003d8e139fdcb6bb327c99a6929081900390910190a3505050505b50505050505050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa0836011811115613c9a57fe5b836013811115613ca657fe5b604080519283526020830191909152600082820152519081900360600190a1826011811115611cbb57fe5b519051111590565b5190511090565b6060600d805480602002602001604051908101604052809291908181526020018280548015613d3857602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311613d1a575b50939450600093505050505b8151811015613dfe576000828281518110613d5b57fe5b60200260200101519050613d6d615c71565b6040518060200160405280836001600160a01b031663aa5af0fd6040518163ffffffff1660e01b815260040160206040518083038186803b158015613db157600080fd5b505afa158015613dc5573d6000803e3d6000fd5b505050506040513d6020811015613ddb57600080fd5b505190529050613dea82614796565b613df482826137f7565b5050600101613d44565b50613e07615c71565b5060408051602081019091526000808252613e20615c71565b5060408051602081019091526000815260105460011415613fe55760005b8451811015613fd1576000858281518110613e5557fe5b6020908102919091018101516001600160a01b0381166000908152600990925260409091206003015490915060ff168015613ea957506001600160a01b0381166000908152600c602052604090205460ff16155b15613fc857613eb6615c71565b6040805160208082018084526004546345bb379f60e01b9091526001600160a01b0386811660248501529351929384939116916345bb379f916044808601929190818703018186803b158015613f0b57600080fd5b505afa158015613f1f573d6000803e3d6000fd5b505050506040513d6020811015613f3557600080fd5b505190529050613f43615c71565b613fb182846001600160a01b03166347bd37186040518163ffffffff1660e01b815260040160206040518083038186803b158015613f8057600080fd5b505afa158015613f94573d6000803e3d6000fd5b505050506040513d6020811015613faa57600080fd5b50516156db565b9050613fbd87826153f8565b965050600190940193505b50600101613e3e565b508115613fe557613fe283836156fc565b90505b613fed615c71565b6040518060200160405280600081525090506060855160405190808252806020026020018201604052801561403c57816020015b614029615c71565b8152602001906001900390816140215790505b50905060005b865181101561428557600087828151811061405957fe5b6020908102919091018101516001600160a01b0381166000908152600990925260409091206003015490915060ff161561427c576001600160a01b038116600090815260166020526040902054806140af575060015b6140b7615c71565b6040805160208082018084526004546345bb379f60e01b9091526001600160a01b0387811660248501529351929384939116916345bb379f916044808601929190818703018186803b15801561410c57600080fd5b505afa158015614120573d6000803e3d6000fd5b505050506040513d602081101561413657600080fd5b505190526010549091506141ca5761414c615c71565b61418982856001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015613f8057600080fd5b9050614193615c71565b61419d82856156db565b9050808787815181106141ac57fe5b60200260200101819052506141c188826153f8565b97505050614279565b6010546001141561043d576001600160a01b0383166000908152600c602052604090205460ff1615614234576141fe615c71565b61420888846156db565b90508086868151811061421757fe5b602002602001018190525061422c87826153f8565b965050614279565b61423c615c71565b61418982856001600160a01b03166347bd37186040518163ffffffff1660e01b815260040160206040518083038186803b158015613f8057600080fd5b50505b50600101614042565b5060005b8651811015613c62576000600d82815481106142a157fe5b600091825260208220015485516001600160a01b0390911692506142c65760006142ee565b6142ee600e546142e98686815181106142db57fe5b60200260200101518861571d565b615750565b6001600160a01b0383166000818152600f602052604090208290558651865192935090917f89405c17a97bc92696f7f9976d71678052010989b8946f2d33a51e6041a56d4f91849188908890811061434257fe5b60200260200101516000015160405180848152602001838152602001828152602001935050505060405180910390a25050600101614289565b6000806000614388615ca8565b6001600160a01b0388166000908152600860209081526040808320805482518185028101850190935280835284936060939291908301828280156143f557602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116143d7575b50939450600093505050505b815181101561475157600082828151811061441857fe5b60200260200101519050806001600160a01b031663c37f68e28e6040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060806040518083038186803b15801561447857600080fd5b505afa15801561448c573d6000803e3d6000fd5b505050506040513d60808110156144a257600080fd5b508051602082015160408084015160609485015160808c0152938a019390935291880191909152945084156144e85750600f975060009650869550611c0d945050505050565b60408051602080820183526001600160a01b0380851660008181526009845285902060010154845260c08b01939093528351808301855260808b0151815260e08b015260048054855163fc57d4df60e01b815291820194909452935192169263fc57d4df9260248083019392829003018186803b15801561456857600080fd5b505afa15801561457c573d6000803e3d6000fd5b505050506040513d602081101561459257600080fd5b505160a087018190526145b65750600d975060009650869550611c0d945050505050565b604080516020810190915260a08701518152610100870181905260c087015160e08801516145e392615769565b610120880152935060008460038111156145f957fe5b146146155750600b975060009650869550611c0d945050505050565b61462d866101200151876040015188600001516157c1565b87529350600084600381111561463f57fe5b1461465b5750600b975060009650869550611c0d945050505050565b614673866101000151876060015188602001516157c1565b60208801529350600084600381111561468857fe5b146146a45750600b975060009650869550611c0d945050505050565b8b6001600160a01b0316816001600160a01b03161415614748576146d28661012001518c88602001516157c1565b6020880152935060008460038111156146e757fe5b146147035750600b975060009650869550611c0d945050505050565b6147178661010001518b88602001516157c1565b60208801529350600084600381111561472c57fe5b146147485750600b975060009650869550611c0d945050505050565b50600101614401565b50602084015184511115614778575050506020810151905160009450039150829050611c0d565b5050815160209092015160009550859450919091039150611c0d9050565b6001600160a01b0381166000908152601160209081526040808320600f90925282205490916147c3611b82565b83549091506000906147e3908390600160e01b900463ffffffff16615320565b90506000811180156147f55750600083115b156149bb576000856001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561483557600080fd5b505afa158015614849573d6000803e3d6000fd5b505050506040513d602081101561485f57600080fd5b50519050600061486f8386615378565b9050614879615c71565b6000831161489657604051806020016040528060008152506148a0565b6148a082846153ba565b90506148aa615c71565b604080516020810190915288546001600160e01b031681526148cc90836153f8565b9050604051806040016040528061491c83600001516040518060400160405280601a81526020017f6e657720696e646578206578636565647320323234206269747300000000000081525061541d565b6001600160e01b03168152602001614957886040518060400160405280601c8152602001600080516020615df78339815191528152506154b7565b63ffffffff9081169091526001600160a01b038b166000908152601160209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b031990941693909317169190911790555061156192505050565b8015611561576149ee826040518060400160405280601c8152602001600080516020615df78339815191528152506154b7565b845463ffffffff91909116600160e01b026001600160e01b039091161784555050505050565b6001600160a01b0383166000908152601160205260409020614a34615c71565b50604080516020810190915281546001600160e01b03168152614a55615c71565b5060408051602080820183526001600160a01b03808916600090815260138352848120918916808252828452948120805485528651959091529152919091558051158015614aa35750815115155b15614abb576ec097ce7bc90715b34b9f100000000081525b614ac3615c71565b614acd838361550c565b90506000876001600160a01b03166370a08231886040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015614b2757600080fd5b505afa158015614b3b573d6000803e3d6000fd5b505050506040513d6020811015614b5157600080fd5b505190506000614b618284615531565b6001600160a01b03891660009081526015602052604081205491925090614b889083615560565b9050614ba289828a613bf657670de0b6b3a7640000613bf9565b6001600160a01b03808b1660008181526015602090815260409182902094909455895181518781529485015280519193928e16927f2caecd17d02f56fa897705dcc740da2d237c373f70686f4e0d9bd3bf0400ea7a929081900390910190a350505050505050505050565b6000806000614c2084600080600061437b565b9250925092509193909250565b6000806000614c3a615c71565b614c44868661580e565b90925090506000826003811115614c5757fe5b14614c685750915060009050614c7a565b6000614c7382615876565b9350935050505b9250929050565b600080546001600160a01b0316331480614ca557506002546001600160a01b031633145b905090565b60005b600d54811015614d3557816001600160a01b0316600d8281548110614cce57fe5b6000918252602090912001546001600160a01b03161415614d2d576040805162461bcd60e51b81526020600482015260146024820152731b585c9ad95d08185b1c9958591e48185919195960621b604482015290519081900360640190fd5b600101614cad565b50600d80546001810182556000919091527fd7b6990105719101dabeb77144f2a3385c8033acd3af97e9423a695e81ad1eb50180546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b03831660009081526009602052604081205460ff16614daf576009611c99565b6001600160a01b038085166000908152600960209081526040808320938716835260029093019052205460ff16614de7576000611c99565b600080614df7858786600061437b565b91935090915060009050826011811115614e0d57fe5b14614e1e5781601181111561317457fe5b8015612ec8576004613174565b6001600160a01b0382166000908152600960205260408120805460ff16614e56576009915050611388565b6001600160a01b038316600090815260028201602052604090205460ff16151560011415614e88576000915050611388565b6007546001600160a01b03841660009081526008602052604090205410614eb3576010915050611388565b6001600160a01b0380841660008181526002840160209081526040808320805460ff19166001908117909155600883528184208054918201815584529282902090920180549489166001600160a01b031990951685179055815193845283019190915280517f3ab23ab0d51cccc0c3085aec51f99228625aa1a922b3a8ca89a26b0f2027a1a59281900390910190a15060009392505050565b6000614f56615c71565b614f7c604051806020016040528086815250604051806020016040528086815250615885565b915091509250929050565b6000614f91615c71565b83518351614f7c919061596e565b6001600160a01b0381166000908152600960205260409020805460ff161515600114615012576040805162461bcd60e51b815260206004820152601960248201527f636f6d70206d61726b6574206973206e6f74206c697374656400000000000000604482015290519081900360640190fd5b600381015460ff161561506c576040805162461bcd60e51b815260206004820152601960248201527f636f6d70206d61726b657420616c726561647920616464656400000000000000604482015290519081900360640190fd5b60038101805460ff19166001908117909155604080516001600160a01b0385168152602081019290925280517f93c1f3e36ed71139f466a4ce8c9751790e2e33f5afb2df0dcfb3aeabe55d5aa29281900390910190a16001600160a01b0382166000908152601160205260409020546001600160e01b031615801561511457506001600160a01b038216600090815260116020526040902054600160e01b900463ffffffff16155b156151d15760405180604001604052806ec097ce7bc90715b34b9f10000000006001600160e01b0316815260200161517661514d611b82565b6040518060400160405280601c8152602001600080516020615df78339815191528152506154b7565b63ffffffff9081169091526001600160a01b0384166000908152601160209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b031990941693909317169190911790555b6001600160a01b0382166000908152601260205260409020546001600160e01b031615801561522357506001600160a01b038216600090815260126020526040902054600160e01b900463ffffffff16155b156119c75760405180604001604052806ec097ce7bc90715b34b9f10000000006001600160e01b0316815260200161525c61514d611b82565b63ffffffff9081169091526001600160a01b0384166000908152601260209081526040909120835181549490920151909216600160e01b026001600160e01b039182166001600160e01b031990941693909317169190911790555050565b60007f45b96fe442630264581b197e84bbada861235052c5a1aadfff9ea4e40a969aa08460118111156152e957fe5b8460138111156152f557fe5b604080519283526020830191909152818101859052519081900360600190a1836011811115611cb857fe5b6000611cbb8383604051806040016040528060158152602001747375627472616374696f6e20756e646572666c6f7760581b815250615a1e565b6000611cbb61537184670de0b6b3a7640000615378565b8351615a78565b6000611cbb83836040518060400160405280601781526020017f6d756c7469706c69636174696f6e206f766572666c6f77000000000000000000815250615aab565b6153c2615c71565b60405180602001604052806153ef6153e9866ec097ce7bc90715b34b9f1000000000615378565b85615a78565b90529392505050565b615400615c71565b60405180602001604052806153ef85600001518560000151615560565b600081600160e01b84106154af5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561547457818101518382015260200161545c565b50505050905090810190601f1680156154a15780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b509192915050565b600081600160201b84106154af5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561547457818101518382015260200161545c565b615514615c71565b60405180602001604052806153ef85600001518560000151615320565b60006ec097ce7bc90715b34b9f1000000000615551848460000151615378565b8161555857fe5b049392505050565b6000611cbb8383604051806040016040528060118152602001706164646974696f6e206f766572666c6f7760781b815250615b2a565b60008183101580156155a85750600083115b156156d35760006155b76123b9565b604080516370a0823160e01b815230600482015290519192506000916001600160a01b038416916370a08231916024808301926020929190829003018186803b15801561560357600080fd5b505afa158015615617573d6000803e3d6000fd5b505050506040513d602081101561562d57600080fd5b505190508085116156d057816001600160a01b031663a9059cbb87876040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050602060405180830381600087803b15801561569857600080fd5b505af11580156156ac573d6000803e3d6000fd5b505050506040513d60208110156156c257600080fd5b5060009350611cbb92505050565b50505b509092915050565b6156e3615c71565b60405180602001604052806153ef856000015185615378565b615704615c71565b60405180602001604052806153ef856000015185615a78565b615725615c71565b60405180602001604052806153ef6157498660000151670de0b6b3a7640000615378565b8551615a78565b6000670de0b6b3a7640000615551848460000151615378565b6000615773615c71565b600061577d615c71565b6157878787615885565b9092509050600082600381111561579a57fe5b146157a9579092509050612c53565b6157b38186615885565b935093505050935093915050565b60008060006157ce615c71565b6157d8878761580e565b909250905060008260038111156157eb57fe5b146157fc5750915060009050612c53565b6157b361580882615876565b86615b7f565b6000615818615c71565b600080615829866000015186615ba5565b9092509050600082600381111561583c57fe5b1461585b57506040805160208101909152600081529092509050614c7a565b60408051602081019091529081526000969095509350505050565b51670de0b6b3a7640000900490565b600061588f615c71565b6000806158a486600001518660000151615ba5565b909250905060008260038111156158b757fe5b146158d657506040805160208101909152600081529092509050614c7a565b6000806158eb6706f05b59d3b2000084615b7f565b909250905060008260038111156158fe57fe5b1461592057506040805160208101909152600081529094509250614c7a915050565b60008061593583670de0b6b3a7640000615be4565b9092509050600082600381111561594857fe5b1461594f57fe5b604080516020810190915290815260009a909950975050505050505050565b6000615978615c71565b60008061598d86670de0b6b3a7640000615ba5565b909250905060008260038111156159a057fe5b146159bf57506040805160208101909152600081529092509050614c7a565b6000806159cc8388615be4565b909250905060008260038111156159df57fe5b14615a0157506040805160208101909152600081529094509250614c7a915050565b604080516020810190915290815260009890975095505050505050565b60008184841115615a705760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561547457818101518382015260200161545c565b505050900390565b6000611cbb83836040518060400160405280600e81526020016d646976696465206279207a65726f60901b815250615c0f565b6000831580615ab8575082155b15615ac557506000611cbb565b83830283858281615ad257fe5b04148390615b215760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561547457818101518382015260200161545c565b50949350505050565b60008383018285821015615b215760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561547457818101518382015260200161545c565b600080838301848110615b9757600092509050614c7a565b506002915060009050614c7a565b60008083615bb857506000905080614c7a565b83830283858281615bc557fe5b0414615bd957506002915060009050614c7a565b600092509050614c7a565b60008082615bf85750600190506000614c7a565b6000838581615c0357fe5b04915091509250929050565b60008183615c5e5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561547457818101518382015260200161545c565b50828481615c6857fe5b04949350505050565b6040518060200160405280600081525090565b8154818355818111156113eb576000838152602090206113eb918101908301615d12565b604051806101400160405280600081526020016000815260200160008152602001600081526020016000815260200160008152602001615ce6615c71565b8152602001615cf3615c71565b8152602001615d00615c71565b8152602001615d0d615c71565b905290565b611b8491905b80821115615d2c5760008155600101615d18565b509056fe63616e6e6f742070617573652061206d61726b65742074686174206973206e6f74206c69737465646f6e6c792061646d696e2063616e206368616e67652063686565736520726174656f6e6c792065787465726e616c6c79206f776e6564206163636f756e7473206d61792072656672657368207370656564736f6e6c7920706175736520677561726469616e20616e642061646d696e2063616e207061757365657869744d61726b65743a206765744163636f756e74536e617073686f74206661696c6564626c6f636b206e756d62657220657863656564732033322062697473000000006f6e6c7920756e6974726f6c6c65722061646d696e2063616e206368616e676520627261696e73a265627a7a723158201641c693c05a3381d866c4ad0253cc48259528d6218982e00aeb07151cb9a54464736f6c63430005110032
[ 0, 7, 24, 15, 17, 9, 12, 16, 5, 18 ]
0x50bEa3c316FA4bFb4Ec0A8546182A81A6d00bac9
pragma solidity 0.5.15; contract MemoryMap { /* We store the state of the verifer in a contiguous chunk of memory. The offsets of the different fields are listed below. E.g. The offset of the i'th hash is [mm_hashes + i]. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; uint256 constant internal MAX_N_QUERIES = 48; uint256 constant internal FRI_QUEUE_SIZE = MAX_N_QUERIES; uint256 constant internal MAX_SUPPORTED_MAX_FRI_STEP = 4; uint256 constant internal MM_EVAL_DOMAIN_SIZE = 0x0; uint256 constant internal MM_BLOW_UP_FACTOR = 0x1; uint256 constant internal MM_LOG_EVAL_DOMAIN_SIZE = 0x2; uint256 constant internal MM_PROOF_OF_WORK_BITS = 0x3; uint256 constant internal MM_EVAL_DOMAIN_GENERATOR = 0x4; uint256 constant internal MM_PUBLIC_INPUT_PTR = 0x5; uint256 constant internal MM_TRACE_COMMITMENT = 0x6; // uint256[2] uint256 constant internal MM_OODS_COMMITMENT = 0x8; uint256 constant internal MM_N_UNIQUE_QUERIES = 0x9; uint256 constant internal MM_CHANNEL = 0xa; // uint256[3] uint256 constant internal MM_MERKLE_QUEUE = 0xd; // uint256[96] uint256 constant internal MM_FRI_QUEUE = 0x6d; // uint256[144] uint256 constant internal MM_FRI_QUERIES_DELIMITER = 0xfd; uint256 constant internal MM_FRI_CTX = 0xfe; // uint256[40] uint256 constant internal MM_FRI_STEPS_PTR = 0x126; uint256 constant internal MM_FRI_EVAL_POINTS = 0x127; // uint256[10] uint256 constant internal MM_FRI_COMMITMENTS = 0x131; // uint256[10] uint256 constant internal MM_FRI_LAST_LAYER_DEG_BOUND = 0x13b; uint256 constant internal MM_FRI_LAST_LAYER_PTR = 0x13c; uint256 constant internal MM_CONSTRAINT_POLY_ARGS_START = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__PEDERSEN__POINTS__X = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__PEDERSEN__POINTS__Y = 0x13e; uint256 constant internal MM_PERIODIC_COLUMN__ECDSA__GENERATOR_POINTS__X = 0x13f; uint256 constant internal MM_PERIODIC_COLUMN__ECDSA__GENERATOR_POINTS__Y = 0x140; uint256 constant internal MM_TRACE_LENGTH = 0x141; uint256 constant internal MM_OFFSET_SIZE = 0x142; uint256 constant internal MM_HALF_OFFSET_SIZE = 0x143; uint256 constant internal MM_INITIAL_AP = 0x144; uint256 constant internal MM_INITIAL_PC = 0x145; uint256 constant internal MM_FINAL_AP = 0x146; uint256 constant internal MM_FINAL_PC = 0x147; uint256 constant internal MM_MEMORY__MULTI_COLUMN_PERM__PERM__INTERACTION_ELM = 0x148; uint256 constant internal MM_MEMORY__MULTI_COLUMN_PERM__HASH_INTERACTION_ELM0 = 0x149; uint256 constant internal MM_MEMORY__MULTI_COLUMN_PERM__PERM__PUBLIC_MEMORY_PROD = 0x14a; uint256 constant internal MM_RC16__PERM__INTERACTION_ELM = 0x14b; uint256 constant internal MM_RC16__PERM__PUBLIC_MEMORY_PROD = 0x14c; uint256 constant internal MM_RC_MIN = 0x14d; uint256 constant internal MM_RC_MAX = 0x14e; uint256 constant internal MM_PEDERSEN__SHIFT_POINT_X = 0x14f; uint256 constant internal MM_PEDERSEN__SHIFT_POINT_Y = 0x150; uint256 constant internal MM_INITIAL_PEDERSEN_ADDR = 0x151; uint256 constant internal MM_INITIAL_RC_ADDR = 0x152; uint256 constant internal MM_ECDSA__SIG_CONFIG_ALPHA = 0x153; uint256 constant internal MM_ECDSA__SIG_CONFIG_SHIFT_POINT_X = 0x154; uint256 constant internal MM_ECDSA__SIG_CONFIG_SHIFT_POINT_Y = 0x155; uint256 constant internal MM_ECDSA__SIG_CONFIG_BETA = 0x156; uint256 constant internal MM_INITIAL_ECDSA_ADDR = 0x157; uint256 constant internal MM_INITIAL_CHECKPOINTS_ADDR = 0x158; uint256 constant internal MM_FINAL_CHECKPOINTS_ADDR = 0x159; uint256 constant internal MM_TRACE_GENERATOR = 0x15a; uint256 constant internal MM_OODS_POINT = 0x15b; uint256 constant internal MM_INTERACTION_ELEMENTS = 0x15c; // uint256[3] uint256 constant internal MM_COEFFICIENTS = 0x15f; // uint256[298] uint256 constant internal MM_OODS_VALUES = 0x289; // uint256[174] uint256 constant internal MM_CONSTRAINT_POLY_ARGS_END = 0x337; uint256 constant internal MM_COMPOSITION_OODS_VALUES = 0x337; // uint256[2] uint256 constant internal MM_OODS_EVAL_POINTS = 0x339; // uint256[48] uint256 constant internal MM_OODS_COEFFICIENTS = 0x369; // uint256[176] uint256 constant internal MM_TRACE_QUERY_RESPONSES = 0x419; // uint256[1200] uint256 constant internal MM_COMPOSITION_QUERY_RESPONSES = 0x8c9; // uint256[96] uint256 constant internal MM_LOG_N_STEPS = 0x929; uint256 constant internal MM_N_PUBLIC_MEM_ENTRIES = 0x92a; uint256 constant internal MM_N_PUBLIC_MEM_PAGES = 0x92b; uint256 constant internal MM_CONTEXT_SIZE = 0x92c; } contract PrimeFieldElement0 { uint256 constant internal K_MODULUS = 0x800000000000011000000000000000000000000000000000000000000000001; uint256 constant internal K_MODULUS_MASK = 0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant internal K_MONTGOMERY_R = 0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1; uint256 constant internal K_MONTGOMERY_R_INV = 0x40000000000001100000000000012100000000000000000000000000000000; uint256 constant internal GENERATOR_VAL = 3; uint256 constant internal ONE_VAL = 1; uint256 constant internal GEN1024_VAL = 0x659d83946a03edd72406af6711825f5653d9e35dc125289a206c054ec89c4f1; function fromMontgomery(uint256 val) internal pure returns (uint256 res) { // uint256 res = fmul(val, kMontgomeryRInv); assembly { res := mulmod(val, 0x40000000000001100000000000012100000000000000000000000000000000, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) { // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field // element. uint256 res = uint256(bs); return fromMontgomery(res); } function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) { //uint256 res = fmul(val, kMontgomeryR); assembly { res := mulmod(val, 0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { //uint256 res = mulmod(a, b, kModulus); assembly { res := mulmod(a, b, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, b, kModulus); assembly { res := addmod(a, b, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, kModulus - b, kModulus); assembly { res := addmod( a, sub(0x800000000000011000000000000000000000000000000000000000000000001, b), 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fpow(uint256 val, uint256 exp) internal view returns (uint256) { return expmod(val, exp, K_MODULUS); } function expmod(uint256 base, uint256 exponent, uint256 modulus) internal view returns (uint256 res) { assembly { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(gas, 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } } function inverse(uint256 val) internal view returns (uint256) { return expmod(val, K_MODULUS - 2, K_MODULUS); } } contract StarkParameters is PrimeFieldElement0 { uint256 constant internal N_COEFFICIENTS = 298; uint256 constant internal N_INTERACTION_ELEMENTS = 3; uint256 constant internal MASK_SIZE = 174; uint256 constant internal N_ROWS_IN_MASK = 77; uint256 constant internal N_COLUMNS_IN_MASK = 25; uint256 constant internal N_COLUMNS_IN_TRACE0 = 23; uint256 constant internal N_COLUMNS_IN_TRACE1 = 2; uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; uint256 constant internal MAX_FRI_STEP = 3; // ---------- // Air specific constants. ---------- uint256 constant internal PUBLIC_MEMORY_STEP = 8; uint256 constant internal PEDERSEN_BUILTIN_RATIO = 8; uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 4; uint256 constant internal RC_BUILTIN_RATIO = 8; uint256 constant internal RC_N_PARTS = 8; uint256 constant internal ECDSA_BUILTIN_RATIO = 512; uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; uint256 constant internal LAYOUT_CODE = 8098989891770344814; uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; } contract CpuOods is MemoryMap, StarkParameters { // For each query point we want to invert (2 + N_ROWS_IN_MASK) items: // The query point itself (x). // The denominator for the constraint polynomial (x-z^constraintDegree) // [(x-(g^rowNumber)z) for rowNumber in mask]. uint256 constant internal BATCH_INVERSE_CHUNK = (2 + N_ROWS_IN_MASK); uint256 constant internal BATCH_INVERSE_SIZE = MAX_N_QUERIES * BATCH_INVERSE_CHUNK; /* Builds and sums boundary constraints that check that the prover provided the proper evaluations out of domain evaluations for the trace and composition columns. The inputs to this function are: The verifier context. The boundary constraints for the trace enforce claims of the form f(g^k*z) = c by requiring the quotient (f(x) - c)/(x-g^k*z) to be a low degree polynomial. The boundary constraints for the composition enforce claims of the form h(z^d) = c by requiring the quotient (h(x) - c)/(x-z^d) to be a low degree polynomial. Where: f is a trace column. h is a composition column. z is the out of domain sampling point. g is the trace generator k is the offset in the mask. d is the degree of the composition polynomial. c is the evaluation sent by the prover. */ function() external { // This funciton assumes that the calldata contains the context as defined in MemoryMap.sol. // Note that ctx is a variable size array so the first uint256 cell contrains it's length. uint256[] memory ctx; assembly { let ctxSize := mul(add(calldataload(0), 1), 0x20) ctx := mload(0x40) mstore(0x40, add(ctx, ctxSize)) calldatacopy(ctx, 0, ctxSize) } uint256[] memory batchInverseArray = new uint256[](2 * BATCH_INVERSE_SIZE); oodsPrepareInverses(ctx, batchInverseArray); uint256 kMontgomeryRInv_ = PrimeFieldElement0.K_MONTGOMERY_R_INV; assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 let kMontgomeryRInv := kMontgomeryRInv_ let context := ctx let friQueue := /*friQueue*/ add(context, 0xdc0) let friQueueEnd := add(friQueue, mul(/*n_unique_queries*/ mload(add(context, 0x140)), 0x60)) let traceQueryResponses := /*traceQueryQesponses*/ add(context, 0x8340) let compositionQueryResponses := /*composition_query_responses*/ add(context, 0x11940) // Set denominatorsPtr to point to the batchInverseOut array. // The content of batchInverseOut is described in oodsPrepareInverses. let denominatorsPtr := add(batchInverseArray, 0x20) for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { // res accumulates numbers modulo PRIME. Since 31*PRIME < 2**256, we may add up to // 31 numbers without fear of overflow, and use addmod modulo PRIME only every // 31 iterations, and once more at the very end. let res := 0 // Trace constraints. // Mask items for column #0. { // Read the next element. let columnValue := mulmod(mload(traceQueryResponses), kMontgomeryRInv, PRIME) // res += c_0*(f_0(x) - f_0(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[0]*/ mload(add(context, 0x6d40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[0]*/ mload(add(context, 0x5140)))), PRIME)) // res += c_1*(f_0(x) - f_0(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[1]*/ mload(add(context, 0x6d60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[1]*/ mload(add(context, 0x5160)))), PRIME)) // res += c_2*(f_0(x) - f_0(g^4 * z)) / (x - g^4 * z). res := add( res, mulmod(mulmod(/*(x - g^4 * z)^(-1)*/ mload(add(denominatorsPtr, 0x80)), /*oods_coefficients[2]*/ mload(add(context, 0x6d80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[2]*/ mload(add(context, 0x5180)))), PRIME)) // res += c_3*(f_0(x) - f_0(g^8 * z)) / (x - g^8 * z). res := add( res, mulmod(mulmod(/*(x - g^8 * z)^(-1)*/ mload(add(denominatorsPtr, 0x100)), /*oods_coefficients[3]*/ mload(add(context, 0x6da0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[3]*/ mload(add(context, 0x51a0)))), PRIME)) // res += c_4*(f_0(x) - f_0(g^12 * z)) / (x - g^12 * z). res := add( res, mulmod(mulmod(/*(x - g^12 * z)^(-1)*/ mload(add(denominatorsPtr, 0x180)), /*oods_coefficients[4]*/ mload(add(context, 0x6dc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[4]*/ mload(add(context, 0x51c0)))), PRIME)) // res += c_5*(f_0(x) - f_0(g^28 * z)) / (x - g^28 * z). res := add( res, mulmod(mulmod(/*(x - g^28 * z)^(-1)*/ mload(add(denominatorsPtr, 0x2e0)), /*oods_coefficients[5]*/ mload(add(context, 0x6de0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[5]*/ mload(add(context, 0x51e0)))), PRIME)) // res += c_6*(f_0(x) - f_0(g^44 * z)) / (x - g^44 * z). res := add( res, mulmod(mulmod(/*(x - g^44 * z)^(-1)*/ mload(add(denominatorsPtr, 0x380)), /*oods_coefficients[6]*/ mload(add(context, 0x6e00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[6]*/ mload(add(context, 0x5200)))), PRIME)) // res += c_7*(f_0(x) - f_0(g^60 * z)) / (x - g^60 * z). res := add( res, mulmod(mulmod(/*(x - g^60 * z)^(-1)*/ mload(add(denominatorsPtr, 0x3c0)), /*oods_coefficients[7]*/ mload(add(context, 0x6e20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[7]*/ mload(add(context, 0x5220)))), PRIME)) // res += c_8*(f_0(x) - f_0(g^76 * z)) / (x - g^76 * z). res := add( res, mulmod(mulmod(/*(x - g^76 * z)^(-1)*/ mload(add(denominatorsPtr, 0x440)), /*oods_coefficients[8]*/ mload(add(context, 0x6e40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[8]*/ mload(add(context, 0x5240)))), PRIME)) // res += c_9*(f_0(x) - f_0(g^92 * z)) / (x - g^92 * z). res := add( res, mulmod(mulmod(/*(x - g^92 * z)^(-1)*/ mload(add(denominatorsPtr, 0x4a0)), /*oods_coefficients[9]*/ mload(add(context, 0x6e60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[9]*/ mload(add(context, 0x5260)))), PRIME)) // res += c_10*(f_0(x) - f_0(g^108 * z)) / (x - g^108 * z). res := add( res, mulmod(mulmod(/*(x - g^108 * z)^(-1)*/ mload(add(denominatorsPtr, 0x500)), /*oods_coefficients[10]*/ mload(add(context, 0x6e80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[10]*/ mload(add(context, 0x5280)))), PRIME)) // res += c_11*(f_0(x) - f_0(g^124 * z)) / (x - g^124 * z). res := add( res, mulmod(mulmod(/*(x - g^124 * z)^(-1)*/ mload(add(denominatorsPtr, 0x520)), /*oods_coefficients[11]*/ mload(add(context, 0x6ea0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[11]*/ mload(add(context, 0x52a0)))), PRIME)) } // Mask items for column #1. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_12*(f_1(x) - f_1(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[12]*/ mload(add(context, 0x6ec0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[12]*/ mload(add(context, 0x52c0)))), PRIME)) // res += c_13*(f_1(x) - f_1(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[13]*/ mload(add(context, 0x6ee0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[13]*/ mload(add(context, 0x52e0)))), PRIME)) // res += c_14*(f_1(x) - f_1(g^2 * z)) / (x - g^2 * z). res := add( res, mulmod(mulmod(/*(x - g^2 * z)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[14]*/ mload(add(context, 0x6f00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[14]*/ mload(add(context, 0x5300)))), PRIME)) // res += c_15*(f_1(x) - f_1(g^3 * z)) / (x - g^3 * z). res := add( res, mulmod(mulmod(/*(x - g^3 * z)^(-1)*/ mload(add(denominatorsPtr, 0x60)), /*oods_coefficients[15]*/ mload(add(context, 0x6f20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[15]*/ mload(add(context, 0x5320)))), PRIME)) // res += c_16*(f_1(x) - f_1(g^4 * z)) / (x - g^4 * z). res := add( res, mulmod(mulmod(/*(x - g^4 * z)^(-1)*/ mload(add(denominatorsPtr, 0x80)), /*oods_coefficients[16]*/ mload(add(context, 0x6f40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[16]*/ mload(add(context, 0x5340)))), PRIME)) // res += c_17*(f_1(x) - f_1(g^5 * z)) / (x - g^5 * z). res := add( res, mulmod(mulmod(/*(x - g^5 * z)^(-1)*/ mload(add(denominatorsPtr, 0xa0)), /*oods_coefficients[17]*/ mload(add(context, 0x6f60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[17]*/ mload(add(context, 0x5360)))), PRIME)) // res += c_18*(f_1(x) - f_1(g^6 * z)) / (x - g^6 * z). res := add( res, mulmod(mulmod(/*(x - g^6 * z)^(-1)*/ mload(add(denominatorsPtr, 0xc0)), /*oods_coefficients[18]*/ mload(add(context, 0x6f80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[18]*/ mload(add(context, 0x5380)))), PRIME)) // res += c_19*(f_1(x) - f_1(g^7 * z)) / (x - g^7 * z). res := add( res, mulmod(mulmod(/*(x - g^7 * z)^(-1)*/ mload(add(denominatorsPtr, 0xe0)), /*oods_coefficients[19]*/ mload(add(context, 0x6fa0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[19]*/ mload(add(context, 0x53a0)))), PRIME)) // res += c_20*(f_1(x) - f_1(g^8 * z)) / (x - g^8 * z). res := add( res, mulmod(mulmod(/*(x - g^8 * z)^(-1)*/ mload(add(denominatorsPtr, 0x100)), /*oods_coefficients[20]*/ mload(add(context, 0x6fc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[20]*/ mload(add(context, 0x53c0)))), PRIME)) // res += c_21*(f_1(x) - f_1(g^9 * z)) / (x - g^9 * z). res := add( res, mulmod(mulmod(/*(x - g^9 * z)^(-1)*/ mload(add(denominatorsPtr, 0x120)), /*oods_coefficients[21]*/ mload(add(context, 0x6fe0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[21]*/ mload(add(context, 0x53e0)))), PRIME)) // res += c_22*(f_1(x) - f_1(g^10 * z)) / (x - g^10 * z). res := add( res, mulmod(mulmod(/*(x - g^10 * z)^(-1)*/ mload(add(denominatorsPtr, 0x140)), /*oods_coefficients[22]*/ mload(add(context, 0x7000)), PRIME), add(columnValue, sub(PRIME, /*oods_values[22]*/ mload(add(context, 0x5400)))), PRIME)) // res += c_23*(f_1(x) - f_1(g^11 * z)) / (x - g^11 * z). res := add( res, mulmod(mulmod(/*(x - g^11 * z)^(-1)*/ mload(add(denominatorsPtr, 0x160)), /*oods_coefficients[23]*/ mload(add(context, 0x7020)), PRIME), add(columnValue, sub(PRIME, /*oods_values[23]*/ mload(add(context, 0x5420)))), PRIME)) // res += c_24*(f_1(x) - f_1(g^12 * z)) / (x - g^12 * z). res := add( res, mulmod(mulmod(/*(x - g^12 * z)^(-1)*/ mload(add(denominatorsPtr, 0x180)), /*oods_coefficients[24]*/ mload(add(context, 0x7040)), PRIME), add(columnValue, sub(PRIME, /*oods_values[24]*/ mload(add(context, 0x5440)))), PRIME)) // res += c_25*(f_1(x) - f_1(g^13 * z)) / (x - g^13 * z). res := add( res, mulmod(mulmod(/*(x - g^13 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1a0)), /*oods_coefficients[25]*/ mload(add(context, 0x7060)), PRIME), add(columnValue, sub(PRIME, /*oods_values[25]*/ mload(add(context, 0x5460)))), PRIME)) // res += c_26*(f_1(x) - f_1(g^14 * z)) / (x - g^14 * z). res := add( res, mulmod(mulmod(/*(x - g^14 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1c0)), /*oods_coefficients[26]*/ mload(add(context, 0x7080)), PRIME), add(columnValue, sub(PRIME, /*oods_values[26]*/ mload(add(context, 0x5480)))), PRIME)) // res += c_27*(f_1(x) - f_1(g^15 * z)) / (x - g^15 * z). res := add( res, mulmod(mulmod(/*(x - g^15 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1e0)), /*oods_coefficients[27]*/ mload(add(context, 0x70a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[27]*/ mload(add(context, 0x54a0)))), PRIME)) } // Mask items for column #2. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x40)), kMontgomeryRInv, PRIME) // res += c_28*(f_2(x) - f_2(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[28]*/ mload(add(context, 0x70c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[28]*/ mload(add(context, 0x54c0)))), PRIME)) // res += c_29*(f_2(x) - f_2(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[29]*/ mload(add(context, 0x70e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[29]*/ mload(add(context, 0x54e0)))), PRIME)) } // Mask items for column #3. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x60)), kMontgomeryRInv, PRIME) // res += c_30*(f_3(x) - f_3(z)) / (x - z). res := addmod( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[30]*/ mload(add(context, 0x7100)), PRIME), add(columnValue, sub(PRIME, /*oods_values[30]*/ mload(add(context, 0x5500)))), PRIME), PRIME) // res += c_31*(f_3(x) - f_3(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[31]*/ mload(add(context, 0x7120)), PRIME), add(columnValue, sub(PRIME, /*oods_values[31]*/ mload(add(context, 0x5520)))), PRIME)) // res += c_32*(f_3(x) - f_3(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[32]*/ mload(add(context, 0x7140)), PRIME), add(columnValue, sub(PRIME, /*oods_values[32]*/ mload(add(context, 0x5540)))), PRIME)) // res += c_33*(f_3(x) - f_3(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[33]*/ mload(add(context, 0x7160)), PRIME), add(columnValue, sub(PRIME, /*oods_values[33]*/ mload(add(context, 0x5560)))), PRIME)) // res += c_34*(f_3(x) - f_3(g^511 * z)) / (x - g^511 * z). res := add( res, mulmod(mulmod(/*(x - g^511 * z)^(-1)*/ mload(add(denominatorsPtr, 0x740)), /*oods_coefficients[34]*/ mload(add(context, 0x7180)), PRIME), add(columnValue, sub(PRIME, /*oods_values[34]*/ mload(add(context, 0x5580)))), PRIME)) } // Mask items for column #4. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x80)), kMontgomeryRInv, PRIME) // res += c_35*(f_4(x) - f_4(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[35]*/ mload(add(context, 0x71a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[35]*/ mload(add(context, 0x55a0)))), PRIME)) // res += c_36*(f_4(x) - f_4(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[36]*/ mload(add(context, 0x71c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[36]*/ mload(add(context, 0x55c0)))), PRIME)) // res += c_37*(f_4(x) - f_4(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[37]*/ mload(add(context, 0x71e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[37]*/ mload(add(context, 0x55e0)))), PRIME)) // res += c_38*(f_4(x) - f_4(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[38]*/ mload(add(context, 0x7200)), PRIME), add(columnValue, sub(PRIME, /*oods_values[38]*/ mload(add(context, 0x5600)))), PRIME)) } // Mask items for column #5. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xa0)), kMontgomeryRInv, PRIME) // res += c_39*(f_5(x) - f_5(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[39]*/ mload(add(context, 0x7220)), PRIME), add(columnValue, sub(PRIME, /*oods_values[39]*/ mload(add(context, 0x5620)))), PRIME)) } // Mask items for column #6. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xc0)), kMontgomeryRInv, PRIME) // res += c_40*(f_6(x) - f_6(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[40]*/ mload(add(context, 0x7240)), PRIME), add(columnValue, sub(PRIME, /*oods_values[40]*/ mload(add(context, 0x5640)))), PRIME)) // res += c_41*(f_6(x) - f_6(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[41]*/ mload(add(context, 0x7260)), PRIME), add(columnValue, sub(PRIME, /*oods_values[41]*/ mload(add(context, 0x5660)))), PRIME)) // res += c_42*(f_6(x) - f_6(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[42]*/ mload(add(context, 0x7280)), PRIME), add(columnValue, sub(PRIME, /*oods_values[42]*/ mload(add(context, 0x5680)))), PRIME)) } // Mask items for column #7. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0xe0)), kMontgomeryRInv, PRIME) // res += c_43*(f_7(x) - f_7(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[43]*/ mload(add(context, 0x72a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[43]*/ mload(add(context, 0x56a0)))), PRIME)) // res += c_44*(f_7(x) - f_7(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[44]*/ mload(add(context, 0x72c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[44]*/ mload(add(context, 0x56c0)))), PRIME)) // res += c_45*(f_7(x) - f_7(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[45]*/ mload(add(context, 0x72e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[45]*/ mload(add(context, 0x56e0)))), PRIME)) // res += c_46*(f_7(x) - f_7(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[46]*/ mload(add(context, 0x7300)), PRIME), add(columnValue, sub(PRIME, /*oods_values[46]*/ mload(add(context, 0x5700)))), PRIME)) // res += c_47*(f_7(x) - f_7(g^511 * z)) / (x - g^511 * z). res := add( res, mulmod(mulmod(/*(x - g^511 * z)^(-1)*/ mload(add(denominatorsPtr, 0x740)), /*oods_coefficients[47]*/ mload(add(context, 0x7320)), PRIME), add(columnValue, sub(PRIME, /*oods_values[47]*/ mload(add(context, 0x5720)))), PRIME)) } // Mask items for column #8. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x100)), kMontgomeryRInv, PRIME) // res += c_48*(f_8(x) - f_8(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[48]*/ mload(add(context, 0x7340)), PRIME), add(columnValue, sub(PRIME, /*oods_values[48]*/ mload(add(context, 0x5740)))), PRIME)) // res += c_49*(f_8(x) - f_8(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[49]*/ mload(add(context, 0x7360)), PRIME), add(columnValue, sub(PRIME, /*oods_values[49]*/ mload(add(context, 0x5760)))), PRIME)) // res += c_50*(f_8(x) - f_8(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[50]*/ mload(add(context, 0x7380)), PRIME), add(columnValue, sub(PRIME, /*oods_values[50]*/ mload(add(context, 0x5780)))), PRIME)) // res += c_51*(f_8(x) - f_8(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[51]*/ mload(add(context, 0x73a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[51]*/ mload(add(context, 0x57a0)))), PRIME)) } // Mask items for column #9. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x120)), kMontgomeryRInv, PRIME) // res += c_52*(f_9(x) - f_9(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[52]*/ mload(add(context, 0x73c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[52]*/ mload(add(context, 0x57c0)))), PRIME)) } // Mask items for column #10. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x140)), kMontgomeryRInv, PRIME) // res += c_53*(f_10(x) - f_10(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[53]*/ mload(add(context, 0x73e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[53]*/ mload(add(context, 0x57e0)))), PRIME)) // res += c_54*(f_10(x) - f_10(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[54]*/ mload(add(context, 0x7400)), PRIME), add(columnValue, sub(PRIME, /*oods_values[54]*/ mload(add(context, 0x5800)))), PRIME)) // res += c_55*(f_10(x) - f_10(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[55]*/ mload(add(context, 0x7420)), PRIME), add(columnValue, sub(PRIME, /*oods_values[55]*/ mload(add(context, 0x5820)))), PRIME)) } // Mask items for column #11. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x160)), kMontgomeryRInv, PRIME) // res += c_56*(f_11(x) - f_11(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[56]*/ mload(add(context, 0x7440)), PRIME), add(columnValue, sub(PRIME, /*oods_values[56]*/ mload(add(context, 0x5840)))), PRIME)) // res += c_57*(f_11(x) - f_11(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[57]*/ mload(add(context, 0x7460)), PRIME), add(columnValue, sub(PRIME, /*oods_values[57]*/ mload(add(context, 0x5860)))), PRIME)) // res += c_58*(f_11(x) - f_11(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[58]*/ mload(add(context, 0x7480)), PRIME), add(columnValue, sub(PRIME, /*oods_values[58]*/ mload(add(context, 0x5880)))), PRIME)) // res += c_59*(f_11(x) - f_11(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[59]*/ mload(add(context, 0x74a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[59]*/ mload(add(context, 0x58a0)))), PRIME)) // res += c_60*(f_11(x) - f_11(g^511 * z)) / (x - g^511 * z). res := add( res, mulmod(mulmod(/*(x - g^511 * z)^(-1)*/ mload(add(denominatorsPtr, 0x740)), /*oods_coefficients[60]*/ mload(add(context, 0x74c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[60]*/ mload(add(context, 0x58c0)))), PRIME)) } // Mask items for column #12. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x180)), kMontgomeryRInv, PRIME) // res += c_61*(f_12(x) - f_12(z)) / (x - z). res := addmod( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[61]*/ mload(add(context, 0x74e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[61]*/ mload(add(context, 0x58e0)))), PRIME), PRIME) // res += c_62*(f_12(x) - f_12(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[62]*/ mload(add(context, 0x7500)), PRIME), add(columnValue, sub(PRIME, /*oods_values[62]*/ mload(add(context, 0x5900)))), PRIME)) // res += c_63*(f_12(x) - f_12(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[63]*/ mload(add(context, 0x7520)), PRIME), add(columnValue, sub(PRIME, /*oods_values[63]*/ mload(add(context, 0x5920)))), PRIME)) // res += c_64*(f_12(x) - f_12(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[64]*/ mload(add(context, 0x7540)), PRIME), add(columnValue, sub(PRIME, /*oods_values[64]*/ mload(add(context, 0x5940)))), PRIME)) } // Mask items for column #13. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1a0)), kMontgomeryRInv, PRIME) // res += c_65*(f_13(x) - f_13(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[65]*/ mload(add(context, 0x7560)), PRIME), add(columnValue, sub(PRIME, /*oods_values[65]*/ mload(add(context, 0x5960)))), PRIME)) } // Mask items for column #14. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1c0)), kMontgomeryRInv, PRIME) // res += c_66*(f_14(x) - f_14(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[66]*/ mload(add(context, 0x7580)), PRIME), add(columnValue, sub(PRIME, /*oods_values[66]*/ mload(add(context, 0x5980)))), PRIME)) // res += c_67*(f_14(x) - f_14(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[67]*/ mload(add(context, 0x75a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[67]*/ mload(add(context, 0x59a0)))), PRIME)) // res += c_68*(f_14(x) - f_14(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[68]*/ mload(add(context, 0x75c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[68]*/ mload(add(context, 0x59c0)))), PRIME)) } // Mask items for column #15. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x1e0)), kMontgomeryRInv, PRIME) // res += c_69*(f_15(x) - f_15(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[69]*/ mload(add(context, 0x75e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[69]*/ mload(add(context, 0x59e0)))), PRIME)) // res += c_70*(f_15(x) - f_15(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[70]*/ mload(add(context, 0x7600)), PRIME), add(columnValue, sub(PRIME, /*oods_values[70]*/ mload(add(context, 0x5a00)))), PRIME)) // res += c_71*(f_15(x) - f_15(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[71]*/ mload(add(context, 0x7620)), PRIME), add(columnValue, sub(PRIME, /*oods_values[71]*/ mload(add(context, 0x5a20)))), PRIME)) // res += c_72*(f_15(x) - f_15(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[72]*/ mload(add(context, 0x7640)), PRIME), add(columnValue, sub(PRIME, /*oods_values[72]*/ mload(add(context, 0x5a40)))), PRIME)) // res += c_73*(f_15(x) - f_15(g^511 * z)) / (x - g^511 * z). res := add( res, mulmod(mulmod(/*(x - g^511 * z)^(-1)*/ mload(add(denominatorsPtr, 0x740)), /*oods_coefficients[73]*/ mload(add(context, 0x7660)), PRIME), add(columnValue, sub(PRIME, /*oods_values[73]*/ mload(add(context, 0x5a60)))), PRIME)) } // Mask items for column #16. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x200)), kMontgomeryRInv, PRIME) // res += c_74*(f_16(x) - f_16(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[74]*/ mload(add(context, 0x7680)), PRIME), add(columnValue, sub(PRIME, /*oods_values[74]*/ mload(add(context, 0x5a80)))), PRIME)) // res += c_75*(f_16(x) - f_16(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[75]*/ mload(add(context, 0x76a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[75]*/ mload(add(context, 0x5aa0)))), PRIME)) // res += c_76*(f_16(x) - f_16(g^255 * z)) / (x - g^255 * z). res := add( res, mulmod(mulmod(/*(x - g^255 * z)^(-1)*/ mload(add(denominatorsPtr, 0x620)), /*oods_coefficients[76]*/ mload(add(context, 0x76c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[76]*/ mload(add(context, 0x5ac0)))), PRIME)) // res += c_77*(f_16(x) - f_16(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[77]*/ mload(add(context, 0x76e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[77]*/ mload(add(context, 0x5ae0)))), PRIME)) } // Mask items for column #17. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x220)), kMontgomeryRInv, PRIME) // res += c_78*(f_17(x) - f_17(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[78]*/ mload(add(context, 0x7700)), PRIME), add(columnValue, sub(PRIME, /*oods_values[78]*/ mload(add(context, 0x5b00)))), PRIME)) } // Mask items for column #18. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x240)), kMontgomeryRInv, PRIME) // res += c_79*(f_18(x) - f_18(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[79]*/ mload(add(context, 0x7720)), PRIME), add(columnValue, sub(PRIME, /*oods_values[79]*/ mload(add(context, 0x5b20)))), PRIME)) // res += c_80*(f_18(x) - f_18(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[80]*/ mload(add(context, 0x7740)), PRIME), add(columnValue, sub(PRIME, /*oods_values[80]*/ mload(add(context, 0x5b40)))), PRIME)) // res += c_81*(f_18(x) - f_18(g^256 * z)) / (x - g^256 * z). res := add( res, mulmod(mulmod(/*(x - g^256 * z)^(-1)*/ mload(add(denominatorsPtr, 0x640)), /*oods_coefficients[81]*/ mload(add(context, 0x7760)), PRIME), add(columnValue, sub(PRIME, /*oods_values[81]*/ mload(add(context, 0x5b60)))), PRIME)) } // Mask items for column #19. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x260)), kMontgomeryRInv, PRIME) // res += c_82*(f_19(x) - f_19(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[82]*/ mload(add(context, 0x7780)), PRIME), add(columnValue, sub(PRIME, /*oods_values[82]*/ mload(add(context, 0x5b80)))), PRIME)) // res += c_83*(f_19(x) - f_19(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[83]*/ mload(add(context, 0x77a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[83]*/ mload(add(context, 0x5ba0)))), PRIME)) // res += c_84*(f_19(x) - f_19(g^2 * z)) / (x - g^2 * z). res := add( res, mulmod(mulmod(/*(x - g^2 * z)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[84]*/ mload(add(context, 0x77c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[84]*/ mload(add(context, 0x5bc0)))), PRIME)) // res += c_85*(f_19(x) - f_19(g^3 * z)) / (x - g^3 * z). res := add( res, mulmod(mulmod(/*(x - g^3 * z)^(-1)*/ mload(add(denominatorsPtr, 0x60)), /*oods_coefficients[85]*/ mload(add(context, 0x77e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[85]*/ mload(add(context, 0x5be0)))), PRIME)) // res += c_86*(f_19(x) - f_19(g^4 * z)) / (x - g^4 * z). res := add( res, mulmod(mulmod(/*(x - g^4 * z)^(-1)*/ mload(add(denominatorsPtr, 0x80)), /*oods_coefficients[86]*/ mload(add(context, 0x7800)), PRIME), add(columnValue, sub(PRIME, /*oods_values[86]*/ mload(add(context, 0x5c00)))), PRIME)) // res += c_87*(f_19(x) - f_19(g^5 * z)) / (x - g^5 * z). res := add( res, mulmod(mulmod(/*(x - g^5 * z)^(-1)*/ mload(add(denominatorsPtr, 0xa0)), /*oods_coefficients[87]*/ mload(add(context, 0x7820)), PRIME), add(columnValue, sub(PRIME, /*oods_values[87]*/ mload(add(context, 0x5c20)))), PRIME)) // res += c_88*(f_19(x) - f_19(g^6 * z)) / (x - g^6 * z). res := add( res, mulmod(mulmod(/*(x - g^6 * z)^(-1)*/ mload(add(denominatorsPtr, 0xc0)), /*oods_coefficients[88]*/ mload(add(context, 0x7840)), PRIME), add(columnValue, sub(PRIME, /*oods_values[88]*/ mload(add(context, 0x5c40)))), PRIME)) // res += c_89*(f_19(x) - f_19(g^7 * z)) / (x - g^7 * z). res := add( res, mulmod(mulmod(/*(x - g^7 * z)^(-1)*/ mload(add(denominatorsPtr, 0xe0)), /*oods_coefficients[89]*/ mload(add(context, 0x7860)), PRIME), add(columnValue, sub(PRIME, /*oods_values[89]*/ mload(add(context, 0x5c60)))), PRIME)) // res += c_90*(f_19(x) - f_19(g^8 * z)) / (x - g^8 * z). res := add( res, mulmod(mulmod(/*(x - g^8 * z)^(-1)*/ mload(add(denominatorsPtr, 0x100)), /*oods_coefficients[90]*/ mload(add(context, 0x7880)), PRIME), add(columnValue, sub(PRIME, /*oods_values[90]*/ mload(add(context, 0x5c80)))), PRIME)) // res += c_91*(f_19(x) - f_19(g^9 * z)) / (x - g^9 * z). res := add( res, mulmod(mulmod(/*(x - g^9 * z)^(-1)*/ mload(add(denominatorsPtr, 0x120)), /*oods_coefficients[91]*/ mload(add(context, 0x78a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[91]*/ mload(add(context, 0x5ca0)))), PRIME)) // res += c_92*(f_19(x) - f_19(g^12 * z)) / (x - g^12 * z). res := addmod( res, mulmod(mulmod(/*(x - g^12 * z)^(-1)*/ mload(add(denominatorsPtr, 0x180)), /*oods_coefficients[92]*/ mload(add(context, 0x78c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[92]*/ mload(add(context, 0x5cc0)))), PRIME), PRIME) // res += c_93*(f_19(x) - f_19(g^13 * z)) / (x - g^13 * z). res := add( res, mulmod(mulmod(/*(x - g^13 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1a0)), /*oods_coefficients[93]*/ mload(add(context, 0x78e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[93]*/ mload(add(context, 0x5ce0)))), PRIME)) // res += c_94*(f_19(x) - f_19(g^16 * z)) / (x - g^16 * z). res := add( res, mulmod(mulmod(/*(x - g^16 * z)^(-1)*/ mload(add(denominatorsPtr, 0x200)), /*oods_coefficients[94]*/ mload(add(context, 0x7900)), PRIME), add(columnValue, sub(PRIME, /*oods_values[94]*/ mload(add(context, 0x5d00)))), PRIME)) // res += c_95*(f_19(x) - f_19(g^22 * z)) / (x - g^22 * z). res := add( res, mulmod(mulmod(/*(x - g^22 * z)^(-1)*/ mload(add(denominatorsPtr, 0x260)), /*oods_coefficients[95]*/ mload(add(context, 0x7920)), PRIME), add(columnValue, sub(PRIME, /*oods_values[95]*/ mload(add(context, 0x5d20)))), PRIME)) // res += c_96*(f_19(x) - f_19(g^23 * z)) / (x - g^23 * z). res := add( res, mulmod(mulmod(/*(x - g^23 * z)^(-1)*/ mload(add(denominatorsPtr, 0x280)), /*oods_coefficients[96]*/ mload(add(context, 0x7940)), PRIME), add(columnValue, sub(PRIME, /*oods_values[96]*/ mload(add(context, 0x5d40)))), PRIME)) // res += c_97*(f_19(x) - f_19(g^38 * z)) / (x - g^38 * z). res := add( res, mulmod(mulmod(/*(x - g^38 * z)^(-1)*/ mload(add(denominatorsPtr, 0x340)), /*oods_coefficients[97]*/ mload(add(context, 0x7960)), PRIME), add(columnValue, sub(PRIME, /*oods_values[97]*/ mload(add(context, 0x5d60)))), PRIME)) // res += c_98*(f_19(x) - f_19(g^39 * z)) / (x - g^39 * z). res := add( res, mulmod(mulmod(/*(x - g^39 * z)^(-1)*/ mload(add(denominatorsPtr, 0x360)), /*oods_coefficients[98]*/ mload(add(context, 0x7980)), PRIME), add(columnValue, sub(PRIME, /*oods_values[98]*/ mload(add(context, 0x5d80)))), PRIME)) // res += c_99*(f_19(x) - f_19(g^70 * z)) / (x - g^70 * z). res := add( res, mulmod(mulmod(/*(x - g^70 * z)^(-1)*/ mload(add(denominatorsPtr, 0x400)), /*oods_coefficients[99]*/ mload(add(context, 0x79a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[99]*/ mload(add(context, 0x5da0)))), PRIME)) // res += c_100*(f_19(x) - f_19(g^71 * z)) / (x - g^71 * z). res := add( res, mulmod(mulmod(/*(x - g^71 * z)^(-1)*/ mload(add(denominatorsPtr, 0x420)), /*oods_coefficients[100]*/ mload(add(context, 0x79c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[100]*/ mload(add(context, 0x5dc0)))), PRIME)) // res += c_101*(f_19(x) - f_19(g^86 * z)) / (x - g^86 * z). res := add( res, mulmod(mulmod(/*(x - g^86 * z)^(-1)*/ mload(add(denominatorsPtr, 0x460)), /*oods_coefficients[101]*/ mload(add(context, 0x79e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[101]*/ mload(add(context, 0x5de0)))), PRIME)) // res += c_102*(f_19(x) - f_19(g^87 * z)) / (x - g^87 * z). res := add( res, mulmod(mulmod(/*(x - g^87 * z)^(-1)*/ mload(add(denominatorsPtr, 0x480)), /*oods_coefficients[102]*/ mload(add(context, 0x7a00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[102]*/ mload(add(context, 0x5e00)))), PRIME)) // res += c_103*(f_19(x) - f_19(g^102 * z)) / (x - g^102 * z). res := add( res, mulmod(mulmod(/*(x - g^102 * z)^(-1)*/ mload(add(denominatorsPtr, 0x4c0)), /*oods_coefficients[103]*/ mload(add(context, 0x7a20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[103]*/ mload(add(context, 0x5e20)))), PRIME)) // res += c_104*(f_19(x) - f_19(g^103 * z)) / (x - g^103 * z). res := add( res, mulmod(mulmod(/*(x - g^103 * z)^(-1)*/ mload(add(denominatorsPtr, 0x4e0)), /*oods_coefficients[104]*/ mload(add(context, 0x7a40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[104]*/ mload(add(context, 0x5e40)))), PRIME)) // res += c_105*(f_19(x) - f_19(g^134 * z)) / (x - g^134 * z). res := add( res, mulmod(mulmod(/*(x - g^134 * z)^(-1)*/ mload(add(denominatorsPtr, 0x540)), /*oods_coefficients[105]*/ mload(add(context, 0x7a60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[105]*/ mload(add(context, 0x5e60)))), PRIME)) // res += c_106*(f_19(x) - f_19(g^135 * z)) / (x - g^135 * z). res := add( res, mulmod(mulmod(/*(x - g^135 * z)^(-1)*/ mload(add(denominatorsPtr, 0x560)), /*oods_coefficients[106]*/ mload(add(context, 0x7a80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[106]*/ mload(add(context, 0x5e80)))), PRIME)) // res += c_107*(f_19(x) - f_19(g^150 * z)) / (x - g^150 * z). res := add( res, mulmod(mulmod(/*(x - g^150 * z)^(-1)*/ mload(add(denominatorsPtr, 0x580)), /*oods_coefficients[107]*/ mload(add(context, 0x7aa0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[107]*/ mload(add(context, 0x5ea0)))), PRIME)) // res += c_108*(f_19(x) - f_19(g^151 * z)) / (x - g^151 * z). res := add( res, mulmod(mulmod(/*(x - g^151 * z)^(-1)*/ mload(add(denominatorsPtr, 0x5a0)), /*oods_coefficients[108]*/ mload(add(context, 0x7ac0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[108]*/ mload(add(context, 0x5ec0)))), PRIME)) // res += c_109*(f_19(x) - f_19(g^167 * z)) / (x - g^167 * z). res := add( res, mulmod(mulmod(/*(x - g^167 * z)^(-1)*/ mload(add(denominatorsPtr, 0x5c0)), /*oods_coefficients[109]*/ mload(add(context, 0x7ae0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[109]*/ mload(add(context, 0x5ee0)))), PRIME)) // res += c_110*(f_19(x) - f_19(g^199 * z)) / (x - g^199 * z). res := add( res, mulmod(mulmod(/*(x - g^199 * z)^(-1)*/ mload(add(denominatorsPtr, 0x5e0)), /*oods_coefficients[110]*/ mload(add(context, 0x7b00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[110]*/ mload(add(context, 0x5f00)))), PRIME)) // res += c_111*(f_19(x) - f_19(g^230 * z)) / (x - g^230 * z). res := add( res, mulmod(mulmod(/*(x - g^230 * z)^(-1)*/ mload(add(denominatorsPtr, 0x600)), /*oods_coefficients[111]*/ mload(add(context, 0x7b20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[111]*/ mload(add(context, 0x5f20)))), PRIME)) // res += c_112*(f_19(x) - f_19(g^263 * z)) / (x - g^263 * z). res := add( res, mulmod(mulmod(/*(x - g^263 * z)^(-1)*/ mload(add(denominatorsPtr, 0x660)), /*oods_coefficients[112]*/ mload(add(context, 0x7b40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[112]*/ mload(add(context, 0x5f40)))), PRIME)) // res += c_113*(f_19(x) - f_19(g^295 * z)) / (x - g^295 * z). res := add( res, mulmod(mulmod(/*(x - g^295 * z)^(-1)*/ mload(add(denominatorsPtr, 0x680)), /*oods_coefficients[113]*/ mload(add(context, 0x7b60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[113]*/ mload(add(context, 0x5f60)))), PRIME)) // res += c_114*(f_19(x) - f_19(g^327 * z)) / (x - g^327 * z). res := add( res, mulmod(mulmod(/*(x - g^327 * z)^(-1)*/ mload(add(denominatorsPtr, 0x6a0)), /*oods_coefficients[114]*/ mload(add(context, 0x7b80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[114]*/ mload(add(context, 0x5f80)))), PRIME)) // res += c_115*(f_19(x) - f_19(g^391 * z)) / (x - g^391 * z). res := add( res, mulmod(mulmod(/*(x - g^391 * z)^(-1)*/ mload(add(denominatorsPtr, 0x6c0)), /*oods_coefficients[115]*/ mload(add(context, 0x7ba0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[115]*/ mload(add(context, 0x5fa0)))), PRIME)) // res += c_116*(f_19(x) - f_19(g^406 * z)) / (x - g^406 * z). res := add( res, mulmod(mulmod(/*(x - g^406 * z)^(-1)*/ mload(add(denominatorsPtr, 0x6e0)), /*oods_coefficients[116]*/ mload(add(context, 0x7bc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[116]*/ mload(add(context, 0x5fc0)))), PRIME)) // res += c_117*(f_19(x) - f_19(g^423 * z)) / (x - g^423 * z). res := add( res, mulmod(mulmod(/*(x - g^423 * z)^(-1)*/ mload(add(denominatorsPtr, 0x700)), /*oods_coefficients[117]*/ mload(add(context, 0x7be0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[117]*/ mload(add(context, 0x5fe0)))), PRIME)) // res += c_118*(f_19(x) - f_19(g^455 * z)) / (x - g^455 * z). res := add( res, mulmod(mulmod(/*(x - g^455 * z)^(-1)*/ mload(add(denominatorsPtr, 0x720)), /*oods_coefficients[118]*/ mload(add(context, 0x7c00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[118]*/ mload(add(context, 0x6000)))), PRIME)) // res += c_119*(f_19(x) - f_19(g^4118 * z)) / (x - g^4118 * z). res := add( res, mulmod(mulmod(/*(x - g^4118 * z)^(-1)*/ mload(add(denominatorsPtr, 0x840)), /*oods_coefficients[119]*/ mload(add(context, 0x7c20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[119]*/ mload(add(context, 0x6020)))), PRIME)) // res += c_120*(f_19(x) - f_19(g^4119 * z)) / (x - g^4119 * z). res := add( res, mulmod(mulmod(/*(x - g^4119 * z)^(-1)*/ mload(add(denominatorsPtr, 0x860)), /*oods_coefficients[120]*/ mload(add(context, 0x7c40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[120]*/ mload(add(context, 0x6040)))), PRIME)) // res += c_121*(f_19(x) - f_19(g^8214 * z)) / (x - g^8214 * z). res := add( res, mulmod(mulmod(/*(x - g^8214 * z)^(-1)*/ mload(add(denominatorsPtr, 0x980)), /*oods_coefficients[121]*/ mload(add(context, 0x7c60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[121]*/ mload(add(context, 0x6060)))), PRIME)) } // Mask items for column #20. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x280)), kMontgomeryRInv, PRIME) // res += c_122*(f_20(x) - f_20(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[122]*/ mload(add(context, 0x7c80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[122]*/ mload(add(context, 0x6080)))), PRIME)) // res += c_123*(f_20(x) - f_20(g * z)) / (x - g * z). res := addmod( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[123]*/ mload(add(context, 0x7ca0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[123]*/ mload(add(context, 0x60a0)))), PRIME), PRIME) // res += c_124*(f_20(x) - f_20(g^2 * z)) / (x - g^2 * z). res := add( res, mulmod(mulmod(/*(x - g^2 * z)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[124]*/ mload(add(context, 0x7cc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[124]*/ mload(add(context, 0x60c0)))), PRIME)) // res += c_125*(f_20(x) - f_20(g^3 * z)) / (x - g^3 * z). res := add( res, mulmod(mulmod(/*(x - g^3 * z)^(-1)*/ mload(add(denominatorsPtr, 0x60)), /*oods_coefficients[125]*/ mload(add(context, 0x7ce0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[125]*/ mload(add(context, 0x60e0)))), PRIME)) } // Mask items for column #21. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x2a0)), kMontgomeryRInv, PRIME) // res += c_126*(f_21(x) - f_21(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[126]*/ mload(add(context, 0x7d00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[126]*/ mload(add(context, 0x6100)))), PRIME)) // res += c_127*(f_21(x) - f_21(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[127]*/ mload(add(context, 0x7d20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[127]*/ mload(add(context, 0x6120)))), PRIME)) // res += c_128*(f_21(x) - f_21(g^2 * z)) / (x - g^2 * z). res := add( res, mulmod(mulmod(/*(x - g^2 * z)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[128]*/ mload(add(context, 0x7d40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[128]*/ mload(add(context, 0x6140)))), PRIME)) // res += c_129*(f_21(x) - f_21(g^3 * z)) / (x - g^3 * z). res := add( res, mulmod(mulmod(/*(x - g^3 * z)^(-1)*/ mload(add(denominatorsPtr, 0x60)), /*oods_coefficients[129]*/ mload(add(context, 0x7d60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[129]*/ mload(add(context, 0x6160)))), PRIME)) // res += c_130*(f_21(x) - f_21(g^4 * z)) / (x - g^4 * z). res := add( res, mulmod(mulmod(/*(x - g^4 * z)^(-1)*/ mload(add(denominatorsPtr, 0x80)), /*oods_coefficients[130]*/ mload(add(context, 0x7d80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[130]*/ mload(add(context, 0x6180)))), PRIME)) // res += c_131*(f_21(x) - f_21(g^5 * z)) / (x - g^5 * z). res := add( res, mulmod(mulmod(/*(x - g^5 * z)^(-1)*/ mload(add(denominatorsPtr, 0xa0)), /*oods_coefficients[131]*/ mload(add(context, 0x7da0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[131]*/ mload(add(context, 0x61a0)))), PRIME)) // res += c_132*(f_21(x) - f_21(g^6 * z)) / (x - g^6 * z). res := add( res, mulmod(mulmod(/*(x - g^6 * z)^(-1)*/ mload(add(denominatorsPtr, 0xc0)), /*oods_coefficients[132]*/ mload(add(context, 0x7dc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[132]*/ mload(add(context, 0x61c0)))), PRIME)) // res += c_133*(f_21(x) - f_21(g^7 * z)) / (x - g^7 * z). res := add( res, mulmod(mulmod(/*(x - g^7 * z)^(-1)*/ mload(add(denominatorsPtr, 0xe0)), /*oods_coefficients[133]*/ mload(add(context, 0x7de0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[133]*/ mload(add(context, 0x61e0)))), PRIME)) // res += c_134*(f_21(x) - f_21(g^8 * z)) / (x - g^8 * z). res := add( res, mulmod(mulmod(/*(x - g^8 * z)^(-1)*/ mload(add(denominatorsPtr, 0x100)), /*oods_coefficients[134]*/ mload(add(context, 0x7e00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[134]*/ mload(add(context, 0x6200)))), PRIME)) // res += c_135*(f_21(x) - f_21(g^9 * z)) / (x - g^9 * z). res := add( res, mulmod(mulmod(/*(x - g^9 * z)^(-1)*/ mload(add(denominatorsPtr, 0x120)), /*oods_coefficients[135]*/ mload(add(context, 0x7e20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[135]*/ mload(add(context, 0x6220)))), PRIME)) // res += c_136*(f_21(x) - f_21(g^10 * z)) / (x - g^10 * z). res := add( res, mulmod(mulmod(/*(x - g^10 * z)^(-1)*/ mload(add(denominatorsPtr, 0x140)), /*oods_coefficients[136]*/ mload(add(context, 0x7e40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[136]*/ mload(add(context, 0x6240)))), PRIME)) // res += c_137*(f_21(x) - f_21(g^11 * z)) / (x - g^11 * z). res := add( res, mulmod(mulmod(/*(x - g^11 * z)^(-1)*/ mload(add(denominatorsPtr, 0x160)), /*oods_coefficients[137]*/ mload(add(context, 0x7e60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[137]*/ mload(add(context, 0x6260)))), PRIME)) // res += c_138*(f_21(x) - f_21(g^12 * z)) / (x - g^12 * z). res := add( res, mulmod(mulmod(/*(x - g^12 * z)^(-1)*/ mload(add(denominatorsPtr, 0x180)), /*oods_coefficients[138]*/ mload(add(context, 0x7e80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[138]*/ mload(add(context, 0x6280)))), PRIME)) // res += c_139*(f_21(x) - f_21(g^13 * z)) / (x - g^13 * z). res := add( res, mulmod(mulmod(/*(x - g^13 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1a0)), /*oods_coefficients[139]*/ mload(add(context, 0x7ea0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[139]*/ mload(add(context, 0x62a0)))), PRIME)) // res += c_140*(f_21(x) - f_21(g^14 * z)) / (x - g^14 * z). res := add( res, mulmod(mulmod(/*(x - g^14 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1c0)), /*oods_coefficients[140]*/ mload(add(context, 0x7ec0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[140]*/ mload(add(context, 0x62c0)))), PRIME)) // res += c_141*(f_21(x) - f_21(g^15 * z)) / (x - g^15 * z). res := add( res, mulmod(mulmod(/*(x - g^15 * z)^(-1)*/ mload(add(denominatorsPtr, 0x1e0)), /*oods_coefficients[141]*/ mload(add(context, 0x7ee0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[141]*/ mload(add(context, 0x62e0)))), PRIME)) // res += c_142*(f_21(x) - f_21(g^16 * z)) / (x - g^16 * z). res := add( res, mulmod(mulmod(/*(x - g^16 * z)^(-1)*/ mload(add(denominatorsPtr, 0x200)), /*oods_coefficients[142]*/ mload(add(context, 0x7f00)), PRIME), add(columnValue, sub(PRIME, /*oods_values[142]*/ mload(add(context, 0x6300)))), PRIME)) // res += c_143*(f_21(x) - f_21(g^19 * z)) / (x - g^19 * z). res := add( res, mulmod(mulmod(/*(x - g^19 * z)^(-1)*/ mload(add(denominatorsPtr, 0x220)), /*oods_coefficients[143]*/ mload(add(context, 0x7f20)), PRIME), add(columnValue, sub(PRIME, /*oods_values[143]*/ mload(add(context, 0x6320)))), PRIME)) // res += c_144*(f_21(x) - f_21(g^21 * z)) / (x - g^21 * z). res := add( res, mulmod(mulmod(/*(x - g^21 * z)^(-1)*/ mload(add(denominatorsPtr, 0x240)), /*oods_coefficients[144]*/ mload(add(context, 0x7f40)), PRIME), add(columnValue, sub(PRIME, /*oods_values[144]*/ mload(add(context, 0x6340)))), PRIME)) // res += c_145*(f_21(x) - f_21(g^22 * z)) / (x - g^22 * z). res := add( res, mulmod(mulmod(/*(x - g^22 * z)^(-1)*/ mload(add(denominatorsPtr, 0x260)), /*oods_coefficients[145]*/ mload(add(context, 0x7f60)), PRIME), add(columnValue, sub(PRIME, /*oods_values[145]*/ mload(add(context, 0x6360)))), PRIME)) // res += c_146*(f_21(x) - f_21(g^23 * z)) / (x - g^23 * z). res := add( res, mulmod(mulmod(/*(x - g^23 * z)^(-1)*/ mload(add(denominatorsPtr, 0x280)), /*oods_coefficients[146]*/ mload(add(context, 0x7f80)), PRIME), add(columnValue, sub(PRIME, /*oods_values[146]*/ mload(add(context, 0x6380)))), PRIME)) // res += c_147*(f_21(x) - f_21(g^24 * z)) / (x - g^24 * z). res := add( res, mulmod(mulmod(/*(x - g^24 * z)^(-1)*/ mload(add(denominatorsPtr, 0x2a0)), /*oods_coefficients[147]*/ mload(add(context, 0x7fa0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[147]*/ mload(add(context, 0x63a0)))), PRIME)) // res += c_148*(f_21(x) - f_21(g^25 * z)) / (x - g^25 * z). res := add( res, mulmod(mulmod(/*(x - g^25 * z)^(-1)*/ mload(add(denominatorsPtr, 0x2c0)), /*oods_coefficients[148]*/ mload(add(context, 0x7fc0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[148]*/ mload(add(context, 0x63c0)))), PRIME)) // res += c_149*(f_21(x) - f_21(g^30 * z)) / (x - g^30 * z). res := add( res, mulmod(mulmod(/*(x - g^30 * z)^(-1)*/ mload(add(denominatorsPtr, 0x300)), /*oods_coefficients[149]*/ mload(add(context, 0x7fe0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[149]*/ mload(add(context, 0x63e0)))), PRIME)) // res += c_150*(f_21(x) - f_21(g^31 * z)) / (x - g^31 * z). res := add( res, mulmod(mulmod(/*(x - g^31 * z)^(-1)*/ mload(add(denominatorsPtr, 0x320)), /*oods_coefficients[150]*/ mload(add(context, 0x8000)), PRIME), add(columnValue, sub(PRIME, /*oods_values[150]*/ mload(add(context, 0x6400)))), PRIME)) // res += c_151*(f_21(x) - f_21(g^39 * z)) / (x - g^39 * z). res := add( res, mulmod(mulmod(/*(x - g^39 * z)^(-1)*/ mload(add(denominatorsPtr, 0x360)), /*oods_coefficients[151]*/ mload(add(context, 0x8020)), PRIME), add(columnValue, sub(PRIME, /*oods_values[151]*/ mload(add(context, 0x6420)))), PRIME)) // res += c_152*(f_21(x) - f_21(g^55 * z)) / (x - g^55 * z). res := add( res, mulmod(mulmod(/*(x - g^55 * z)^(-1)*/ mload(add(denominatorsPtr, 0x3a0)), /*oods_coefficients[152]*/ mload(add(context, 0x8040)), PRIME), add(columnValue, sub(PRIME, /*oods_values[152]*/ mload(add(context, 0x6440)))), PRIME)) // res += c_153*(f_21(x) - f_21(g^63 * z)) / (x - g^63 * z). res := add( res, mulmod(mulmod(/*(x - g^63 * z)^(-1)*/ mload(add(denominatorsPtr, 0x3e0)), /*oods_coefficients[153]*/ mload(add(context, 0x8060)), PRIME), add(columnValue, sub(PRIME, /*oods_values[153]*/ mload(add(context, 0x6460)))), PRIME)) // res += c_154*(f_21(x) - f_21(g^4081 * z)) / (x - g^4081 * z). res := addmod( res, mulmod(mulmod(/*(x - g^4081 * z)^(-1)*/ mload(add(denominatorsPtr, 0x760)), /*oods_coefficients[154]*/ mload(add(context, 0x8080)), PRIME), add(columnValue, sub(PRIME, /*oods_values[154]*/ mload(add(context, 0x6480)))), PRIME), PRIME) // res += c_155*(f_21(x) - f_21(g^4085 * z)) / (x - g^4085 * z). res := add( res, mulmod(mulmod(/*(x - g^4085 * z)^(-1)*/ mload(add(denominatorsPtr, 0x780)), /*oods_coefficients[155]*/ mload(add(context, 0x80a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[155]*/ mload(add(context, 0x64a0)))), PRIME)) // res += c_156*(f_21(x) - f_21(g^4089 * z)) / (x - g^4089 * z). res := add( res, mulmod(mulmod(/*(x - g^4089 * z)^(-1)*/ mload(add(denominatorsPtr, 0x7a0)), /*oods_coefficients[156]*/ mload(add(context, 0x80c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[156]*/ mload(add(context, 0x64c0)))), PRIME)) // res += c_157*(f_21(x) - f_21(g^4091 * z)) / (x - g^4091 * z). res := add( res, mulmod(mulmod(/*(x - g^4091 * z)^(-1)*/ mload(add(denominatorsPtr, 0x7c0)), /*oods_coefficients[157]*/ mload(add(context, 0x80e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[157]*/ mload(add(context, 0x64e0)))), PRIME)) // res += c_158*(f_21(x) - f_21(g^4093 * z)) / (x - g^4093 * z). res := add( res, mulmod(mulmod(/*(x - g^4093 * z)^(-1)*/ mload(add(denominatorsPtr, 0x7e0)), /*oods_coefficients[158]*/ mload(add(context, 0x8100)), PRIME), add(columnValue, sub(PRIME, /*oods_values[158]*/ mload(add(context, 0x6500)))), PRIME)) // res += c_159*(f_21(x) - f_21(g^4102 * z)) / (x - g^4102 * z). res := add( res, mulmod(mulmod(/*(x - g^4102 * z)^(-1)*/ mload(add(denominatorsPtr, 0x800)), /*oods_coefficients[159]*/ mload(add(context, 0x8120)), PRIME), add(columnValue, sub(PRIME, /*oods_values[159]*/ mload(add(context, 0x6520)))), PRIME)) // res += c_160*(f_21(x) - f_21(g^4110 * z)) / (x - g^4110 * z). res := add( res, mulmod(mulmod(/*(x - g^4110 * z)^(-1)*/ mload(add(denominatorsPtr, 0x820)), /*oods_coefficients[160]*/ mload(add(context, 0x8140)), PRIME), add(columnValue, sub(PRIME, /*oods_values[160]*/ mload(add(context, 0x6540)))), PRIME)) // res += c_161*(f_21(x) - f_21(g^8167 * z)) / (x - g^8167 * z). res := add( res, mulmod(mulmod(/*(x - g^8167 * z)^(-1)*/ mload(add(denominatorsPtr, 0x8a0)), /*oods_coefficients[161]*/ mload(add(context, 0x8160)), PRIME), add(columnValue, sub(PRIME, /*oods_values[161]*/ mload(add(context, 0x6560)))), PRIME)) // res += c_162*(f_21(x) - f_21(g^8175 * z)) / (x - g^8175 * z). res := add( res, mulmod(mulmod(/*(x - g^8175 * z)^(-1)*/ mload(add(denominatorsPtr, 0x8c0)), /*oods_coefficients[162]*/ mload(add(context, 0x8180)), PRIME), add(columnValue, sub(PRIME, /*oods_values[162]*/ mload(add(context, 0x6580)))), PRIME)) // res += c_163*(f_21(x) - f_21(g^8177 * z)) / (x - g^8177 * z). res := add( res, mulmod(mulmod(/*(x - g^8177 * z)^(-1)*/ mload(add(denominatorsPtr, 0x8e0)), /*oods_coefficients[163]*/ mload(add(context, 0x81a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[163]*/ mload(add(context, 0x65a0)))), PRIME)) // res += c_164*(f_21(x) - f_21(g^8181 * z)) / (x - g^8181 * z). res := add( res, mulmod(mulmod(/*(x - g^8181 * z)^(-1)*/ mload(add(denominatorsPtr, 0x900)), /*oods_coefficients[164]*/ mload(add(context, 0x81c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[164]*/ mload(add(context, 0x65c0)))), PRIME)) // res += c_165*(f_21(x) - f_21(g^8183 * z)) / (x - g^8183 * z). res := add( res, mulmod(mulmod(/*(x - g^8183 * z)^(-1)*/ mload(add(denominatorsPtr, 0x920)), /*oods_coefficients[165]*/ mload(add(context, 0x81e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[165]*/ mload(add(context, 0x65e0)))), PRIME)) // res += c_166*(f_21(x) - f_21(g^8185 * z)) / (x - g^8185 * z). res := add( res, mulmod(mulmod(/*(x - g^8185 * z)^(-1)*/ mload(add(denominatorsPtr, 0x940)), /*oods_coefficients[166]*/ mload(add(context, 0x8200)), PRIME), add(columnValue, sub(PRIME, /*oods_values[166]*/ mload(add(context, 0x6600)))), PRIME)) // res += c_167*(f_21(x) - f_21(g^8189 * z)) / (x - g^8189 * z). res := add( res, mulmod(mulmod(/*(x - g^8189 * z)^(-1)*/ mload(add(denominatorsPtr, 0x960)), /*oods_coefficients[167]*/ mload(add(context, 0x8220)), PRIME), add(columnValue, sub(PRIME, /*oods_values[167]*/ mload(add(context, 0x6620)))), PRIME)) } // Mask items for column #22. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x2c0)), kMontgomeryRInv, PRIME) // res += c_168*(f_22(x) - f_22(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[168]*/ mload(add(context, 0x8240)), PRIME), add(columnValue, sub(PRIME, /*oods_values[168]*/ mload(add(context, 0x6640)))), PRIME)) // res += c_169*(f_22(x) - f_22(g^8160 * z)) / (x - g^8160 * z). res := add( res, mulmod(mulmod(/*(x - g^8160 * z)^(-1)*/ mload(add(denominatorsPtr, 0x880)), /*oods_coefficients[169]*/ mload(add(context, 0x8260)), PRIME), add(columnValue, sub(PRIME, /*oods_values[169]*/ mload(add(context, 0x6660)))), PRIME)) } // Mask items for column #23. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x2e0)), kMontgomeryRInv, PRIME) // res += c_170*(f_23(x) - f_23(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[170]*/ mload(add(context, 0x8280)), PRIME), add(columnValue, sub(PRIME, /*oods_values[170]*/ mload(add(context, 0x6680)))), PRIME)) // res += c_171*(f_23(x) - f_23(g * z)) / (x - g * z). res := add( res, mulmod(mulmod(/*(x - g * z)^(-1)*/ mload(add(denominatorsPtr, 0x20)), /*oods_coefficients[171]*/ mload(add(context, 0x82a0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[171]*/ mload(add(context, 0x66a0)))), PRIME)) } // Mask items for column #24. { // Read the next element. let columnValue := mulmod(mload(add(traceQueryResponses, 0x300)), kMontgomeryRInv, PRIME) // res += c_172*(f_24(x) - f_24(z)) / (x - z). res := add( res, mulmod(mulmod(/*(x - z)^(-1)*/ mload(denominatorsPtr), /*oods_coefficients[172]*/ mload(add(context, 0x82c0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[172]*/ mload(add(context, 0x66c0)))), PRIME)) // res += c_173*(f_24(x) - f_24(g^2 * z)) / (x - g^2 * z). res := add( res, mulmod(mulmod(/*(x - g^2 * z)^(-1)*/ mload(add(denominatorsPtr, 0x40)), /*oods_coefficients[173]*/ mload(add(context, 0x82e0)), PRIME), add(columnValue, sub(PRIME, /*oods_values[173]*/ mload(add(context, 0x66e0)))), PRIME)) } // Advance traceQueryResponses by amount read (0x20 * nTraceColumns). traceQueryResponses := add(traceQueryResponses, 0x320) // Composition constraints. { // Read the next element. let columnValue := mulmod(mload(compositionQueryResponses), kMontgomeryRInv, PRIME) // res += c_174*(h_0(x) - C_0(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x9a0)), /*oods_coefficients[174]*/ mload(add(context, 0x8300)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[0]*/ mload(add(context, 0x6700)))), PRIME)) } { // Read the next element. let columnValue := mulmod(mload(add(compositionQueryResponses, 0x20)), kMontgomeryRInv, PRIME) // res += c_175*(h_1(x) - C_1(z^2)) / (x - z^2). res := add( res, mulmod(mulmod(/*(x - z^2)^(-1)*/ mload(add(denominatorsPtr, 0x9a0)), /*oods_coefficients[175]*/ mload(add(context, 0x8320)), PRIME), add(columnValue, sub(PRIME, /*composition_oods_values[1]*/ mload(add(context, 0x6720)))), PRIME)) } // Advance compositionQueryResponses by amount read (0x20 * constraintDegree). compositionQueryResponses := add(compositionQueryResponses, 0x40) // Append the friValue, which is the sum of the out-of-domain-sampling boundary // constraints for the trace and composition polynomials, to the friQueue array. mstore(add(friQueue, 0x20), mod(res, PRIME)) // Append the friInvPoint of the current query to the friQueue array. mstore(add(friQueue, 0x40), /*friInvPoint*/ mload(add(denominatorsPtr,0x9c0))) // Advance denominatorsPtr by chunk size (0x20 * (2+N_ROWS_IN_MASK)). denominatorsPtr := add(denominatorsPtr, 0x9e0) } return(/*friQueue*/ add(context, 0xdc0), 0x1200) } } /* Computes and performs batch inverse on all the denominators required for the out of domain sampling boundary constraints. Since the friEvalPoints are calculated during the computation of the denominators this function also adds those to the batch inverse in prepartion for the fri that follows. After this function returns, the batch_inverse_out array holds #queries chunks of size (2 + N_ROWS_IN_MASK) with the following structure: 0..(N_ROWS_IN_MASK-1): [(x - g^i * z)^(-1) for i in rowsInMask] N_ROWS_IN_MASK: (x - z^constraintDegree)^-1 N_ROWS_IN_MASK+1: friEvalPointInv. */ function oodsPrepareInverses( uint256[] memory context, uint256[] memory batchInverseArray) internal view { uint256 evalCosetOffset_ = PrimeFieldElement0.GENERATOR_VAL; // The array expmodsAndPoints stores subexpressions that are needed // for the denominators computation. // The array is segmented as follows: // expmodsAndPoints[0:19] (.expmods) expmods used during calculations of the points below. // expmodsAndPoints[19:96] (.points) points used during the denominators calculation. uint256[96] memory expmodsAndPoints; assembly { function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let traceGenerator := /*trace_generator*/ mload(add(context, 0x2b60)) let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 // Prepare expmods for computations of trace generator powers. // expmodsAndPoints.expmods[0] = traceGenerator^2. mstore(expmodsAndPoints, mulmod(traceGenerator, // traceGenerator^1 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[1] = traceGenerator^3. mstore(add(expmodsAndPoints, 0x20), mulmod(mload(expmodsAndPoints), // traceGenerator^2 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[2] = traceGenerator^4. mstore(add(expmodsAndPoints, 0x40), mulmod(mload(add(expmodsAndPoints, 0x20)), // traceGenerator^3 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[3] = traceGenerator^5. mstore(add(expmodsAndPoints, 0x60), mulmod(mload(add(expmodsAndPoints, 0x40)), // traceGenerator^4 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[4] = traceGenerator^7. mstore(add(expmodsAndPoints, 0x80), mulmod(mload(add(expmodsAndPoints, 0x60)), // traceGenerator^5 mload(expmodsAndPoints), // traceGenerator^2 PRIME)) // expmodsAndPoints.expmods[5] = traceGenerator^8. mstore(add(expmodsAndPoints, 0xa0), mulmod(mload(add(expmodsAndPoints, 0x80)), // traceGenerator^7 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[6] = traceGenerator^9. mstore(add(expmodsAndPoints, 0xc0), mulmod(mload(add(expmodsAndPoints, 0xa0)), // traceGenerator^8 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[7] = traceGenerator^10. mstore(add(expmodsAndPoints, 0xe0), mulmod(mload(add(expmodsAndPoints, 0xc0)), // traceGenerator^9 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[8] = traceGenerator^11. mstore(add(expmodsAndPoints, 0x100), mulmod(mload(add(expmodsAndPoints, 0xe0)), // traceGenerator^10 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[9] = traceGenerator^15. mstore(add(expmodsAndPoints, 0x120), mulmod(mload(add(expmodsAndPoints, 0x100)), // traceGenerator^11 mload(add(expmodsAndPoints, 0x40)), // traceGenerator^4 PRIME)) // expmodsAndPoints.expmods[10] = traceGenerator^16. mstore(add(expmodsAndPoints, 0x140), mulmod(mload(add(expmodsAndPoints, 0x120)), // traceGenerator^15 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[11] = traceGenerator^17. mstore(add(expmodsAndPoints, 0x160), mulmod(mload(add(expmodsAndPoints, 0x140)), // traceGenerator^16 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[12] = traceGenerator^25. mstore(add(expmodsAndPoints, 0x180), mulmod(mload(add(expmodsAndPoints, 0x160)), // traceGenerator^17 mload(add(expmodsAndPoints, 0xa0)), // traceGenerator^8 PRIME)) // expmodsAndPoints.expmods[13] = traceGenerator^31. mstore(add(expmodsAndPoints, 0x1a0), mulmod(mload(add(expmodsAndPoints, 0x140)), // traceGenerator^16 mload(add(expmodsAndPoints, 0x120)), // traceGenerator^15 PRIME)) // expmodsAndPoints.expmods[14] = traceGenerator^32. mstore(add(expmodsAndPoints, 0x1c0), mulmod(mload(add(expmodsAndPoints, 0x1a0)), // traceGenerator^31 traceGenerator, // traceGenerator^1 PRIME)) // expmodsAndPoints.expmods[15] = traceGenerator^56. mstore(add(expmodsAndPoints, 0x1e0), mulmod(mload(add(expmodsAndPoints, 0x1a0)), // traceGenerator^31 mload(add(expmodsAndPoints, 0x180)), // traceGenerator^25 PRIME)) // expmodsAndPoints.expmods[16] = traceGenerator^64. mstore(add(expmodsAndPoints, 0x200), mulmod(mload(add(expmodsAndPoints, 0x1e0)), // traceGenerator^56 mload(add(expmodsAndPoints, 0xa0)), // traceGenerator^8 PRIME)) // expmodsAndPoints.expmods[17] = traceGenerator^3570. mstore(add(expmodsAndPoints, 0x220), expmod(traceGenerator, 3570, PRIME)) // expmodsAndPoints.expmods[18] = traceGenerator^4041. mstore(add(expmodsAndPoints, 0x240), expmod(traceGenerator, 4041, PRIME)) let oodsPoint := /*oods_point*/ mload(add(context, 0x2b80)) { // point = -z. let point := sub(PRIME, oodsPoint) // Compute denominators for rows with nonconst mask expression. // We compute those first because for the const rows we modify the point variable. // Compute denominators for rows with const mask expression. // expmods_and_points.points[0] = -z. mstore(add(expmodsAndPoints, 0x260), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[1] = -(g * z). mstore(add(expmodsAndPoints, 0x280), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[2] = -(g^2 * z). mstore(add(expmodsAndPoints, 0x2a0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[3] = -(g^3 * z). mstore(add(expmodsAndPoints, 0x2c0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[4] = -(g^4 * z). mstore(add(expmodsAndPoints, 0x2e0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[5] = -(g^5 * z). mstore(add(expmodsAndPoints, 0x300), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[6] = -(g^6 * z). mstore(add(expmodsAndPoints, 0x320), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[7] = -(g^7 * z). mstore(add(expmodsAndPoints, 0x340), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[8] = -(g^8 * z). mstore(add(expmodsAndPoints, 0x360), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[9] = -(g^9 * z). mstore(add(expmodsAndPoints, 0x380), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[10] = -(g^10 * z). mstore(add(expmodsAndPoints, 0x3a0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[11] = -(g^11 * z). mstore(add(expmodsAndPoints, 0x3c0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[12] = -(g^12 * z). mstore(add(expmodsAndPoints, 0x3e0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[13] = -(g^13 * z). mstore(add(expmodsAndPoints, 0x400), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[14] = -(g^14 * z). mstore(add(expmodsAndPoints, 0x420), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[15] = -(g^15 * z). mstore(add(expmodsAndPoints, 0x440), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[16] = -(g^16 * z). mstore(add(expmodsAndPoints, 0x460), point) // point *= g^3. point := mulmod(point, /*traceGenerator^3*/ mload(add(expmodsAndPoints, 0x20)), PRIME) // expmods_and_points.points[17] = -(g^19 * z). mstore(add(expmodsAndPoints, 0x480), point) // point *= g^2. point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME) // expmods_and_points.points[18] = -(g^21 * z). mstore(add(expmodsAndPoints, 0x4a0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[19] = -(g^22 * z). mstore(add(expmodsAndPoints, 0x4c0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[20] = -(g^23 * z). mstore(add(expmodsAndPoints, 0x4e0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[21] = -(g^24 * z). mstore(add(expmodsAndPoints, 0x500), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[22] = -(g^25 * z). mstore(add(expmodsAndPoints, 0x520), point) // point *= g^3. point := mulmod(point, /*traceGenerator^3*/ mload(add(expmodsAndPoints, 0x20)), PRIME) // expmods_and_points.points[23] = -(g^28 * z). mstore(add(expmodsAndPoints, 0x540), point) // point *= g^2. point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME) // expmods_and_points.points[24] = -(g^30 * z). mstore(add(expmodsAndPoints, 0x560), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[25] = -(g^31 * z). mstore(add(expmodsAndPoints, 0x580), point) // point *= g^7. point := mulmod(point, /*traceGenerator^7*/ mload(add(expmodsAndPoints, 0x80)), PRIME) // expmods_and_points.points[26] = -(g^38 * z). mstore(add(expmodsAndPoints, 0x5a0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[27] = -(g^39 * z). mstore(add(expmodsAndPoints, 0x5c0), point) // point *= g^5. point := mulmod(point, /*traceGenerator^5*/ mload(add(expmodsAndPoints, 0x60)), PRIME) // expmods_and_points.points[28] = -(g^44 * z). mstore(add(expmodsAndPoints, 0x5e0), point) // point *= g^11. point := mulmod(point, /*traceGenerator^11*/ mload(add(expmodsAndPoints, 0x100)), PRIME) // expmods_and_points.points[29] = -(g^55 * z). mstore(add(expmodsAndPoints, 0x600), point) // point *= g^5. point := mulmod(point, /*traceGenerator^5*/ mload(add(expmodsAndPoints, 0x60)), PRIME) // expmods_and_points.points[30] = -(g^60 * z). mstore(add(expmodsAndPoints, 0x620), point) // point *= g^3. point := mulmod(point, /*traceGenerator^3*/ mload(add(expmodsAndPoints, 0x20)), PRIME) // expmods_and_points.points[31] = -(g^63 * z). mstore(add(expmodsAndPoints, 0x640), point) // point *= g^7. point := mulmod(point, /*traceGenerator^7*/ mload(add(expmodsAndPoints, 0x80)), PRIME) // expmods_and_points.points[32] = -(g^70 * z). mstore(add(expmodsAndPoints, 0x660), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[33] = -(g^71 * z). mstore(add(expmodsAndPoints, 0x680), point) // point *= g^5. point := mulmod(point, /*traceGenerator^5*/ mload(add(expmodsAndPoints, 0x60)), PRIME) // expmods_and_points.points[34] = -(g^76 * z). mstore(add(expmodsAndPoints, 0x6a0), point) // point *= g^10. point := mulmod(point, /*traceGenerator^10*/ mload(add(expmodsAndPoints, 0xe0)), PRIME) // expmods_and_points.points[35] = -(g^86 * z). mstore(add(expmodsAndPoints, 0x6c0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[36] = -(g^87 * z). mstore(add(expmodsAndPoints, 0x6e0), point) // point *= g^5. point := mulmod(point, /*traceGenerator^5*/ mload(add(expmodsAndPoints, 0x60)), PRIME) // expmods_and_points.points[37] = -(g^92 * z). mstore(add(expmodsAndPoints, 0x700), point) // point *= g^10. point := mulmod(point, /*traceGenerator^10*/ mload(add(expmodsAndPoints, 0xe0)), PRIME) // expmods_and_points.points[38] = -(g^102 * z). mstore(add(expmodsAndPoints, 0x720), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[39] = -(g^103 * z). mstore(add(expmodsAndPoints, 0x740), point) // point *= g^5. point := mulmod(point, /*traceGenerator^5*/ mload(add(expmodsAndPoints, 0x60)), PRIME) // expmods_and_points.points[40] = -(g^108 * z). mstore(add(expmodsAndPoints, 0x760), point) // point *= g^16. point := mulmod(point, /*traceGenerator^16*/ mload(add(expmodsAndPoints, 0x140)), PRIME) // expmods_and_points.points[41] = -(g^124 * z). mstore(add(expmodsAndPoints, 0x780), point) // point *= g^10. point := mulmod(point, /*traceGenerator^10*/ mload(add(expmodsAndPoints, 0xe0)), PRIME) // expmods_and_points.points[42] = -(g^134 * z). mstore(add(expmodsAndPoints, 0x7a0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[43] = -(g^135 * z). mstore(add(expmodsAndPoints, 0x7c0), point) // point *= g^15. point := mulmod(point, /*traceGenerator^15*/ mload(add(expmodsAndPoints, 0x120)), PRIME) // expmods_and_points.points[44] = -(g^150 * z). mstore(add(expmodsAndPoints, 0x7e0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[45] = -(g^151 * z). mstore(add(expmodsAndPoints, 0x800), point) // point *= g^16. point := mulmod(point, /*traceGenerator^16*/ mload(add(expmodsAndPoints, 0x140)), PRIME) // expmods_and_points.points[46] = -(g^167 * z). mstore(add(expmodsAndPoints, 0x820), point) // point *= g^32. point := mulmod(point, /*traceGenerator^32*/ mload(add(expmodsAndPoints, 0x1c0)), PRIME) // expmods_and_points.points[47] = -(g^199 * z). mstore(add(expmodsAndPoints, 0x840), point) // point *= g^31. point := mulmod(point, /*traceGenerator^31*/ mload(add(expmodsAndPoints, 0x1a0)), PRIME) // expmods_and_points.points[48] = -(g^230 * z). mstore(add(expmodsAndPoints, 0x860), point) // point *= g^25. point := mulmod(point, /*traceGenerator^25*/ mload(add(expmodsAndPoints, 0x180)), PRIME) // expmods_and_points.points[49] = -(g^255 * z). mstore(add(expmodsAndPoints, 0x880), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[50] = -(g^256 * z). mstore(add(expmodsAndPoints, 0x8a0), point) // point *= g^7. point := mulmod(point, /*traceGenerator^7*/ mload(add(expmodsAndPoints, 0x80)), PRIME) // expmods_and_points.points[51] = -(g^263 * z). mstore(add(expmodsAndPoints, 0x8c0), point) // point *= g^32. point := mulmod(point, /*traceGenerator^32*/ mload(add(expmodsAndPoints, 0x1c0)), PRIME) // expmods_and_points.points[52] = -(g^295 * z). mstore(add(expmodsAndPoints, 0x8e0), point) // point *= g^32. point := mulmod(point, /*traceGenerator^32*/ mload(add(expmodsAndPoints, 0x1c0)), PRIME) // expmods_and_points.points[53] = -(g^327 * z). mstore(add(expmodsAndPoints, 0x900), point) // point *= g^64. point := mulmod(point, /*traceGenerator^64*/ mload(add(expmodsAndPoints, 0x200)), PRIME) // expmods_and_points.points[54] = -(g^391 * z). mstore(add(expmodsAndPoints, 0x920), point) // point *= g^15. point := mulmod(point, /*traceGenerator^15*/ mload(add(expmodsAndPoints, 0x120)), PRIME) // expmods_and_points.points[55] = -(g^406 * z). mstore(add(expmodsAndPoints, 0x940), point) // point *= g^17. point := mulmod(point, /*traceGenerator^17*/ mload(add(expmodsAndPoints, 0x160)), PRIME) // expmods_and_points.points[56] = -(g^423 * z). mstore(add(expmodsAndPoints, 0x960), point) // point *= g^32. point := mulmod(point, /*traceGenerator^32*/ mload(add(expmodsAndPoints, 0x1c0)), PRIME) // expmods_and_points.points[57] = -(g^455 * z). mstore(add(expmodsAndPoints, 0x980), point) // point *= g^56. point := mulmod(point, /*traceGenerator^56*/ mload(add(expmodsAndPoints, 0x1e0)), PRIME) // expmods_and_points.points[58] = -(g^511 * z). mstore(add(expmodsAndPoints, 0x9a0), point) // point *= g^3570. point := mulmod(point, /*traceGenerator^3570*/ mload(add(expmodsAndPoints, 0x220)), PRIME) // expmods_and_points.points[59] = -(g^4081 * z). mstore(add(expmodsAndPoints, 0x9c0), point) // point *= g^4. point := mulmod(point, /*traceGenerator^4*/ mload(add(expmodsAndPoints, 0x40)), PRIME) // expmods_and_points.points[60] = -(g^4085 * z). mstore(add(expmodsAndPoints, 0x9e0), point) // point *= g^4. point := mulmod(point, /*traceGenerator^4*/ mload(add(expmodsAndPoints, 0x40)), PRIME) // expmods_and_points.points[61] = -(g^4089 * z). mstore(add(expmodsAndPoints, 0xa00), point) // point *= g^2. point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME) // expmods_and_points.points[62] = -(g^4091 * z). mstore(add(expmodsAndPoints, 0xa20), point) // point *= g^2. point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME) // expmods_and_points.points[63] = -(g^4093 * z). mstore(add(expmodsAndPoints, 0xa40), point) // point *= g^9. point := mulmod(point, /*traceGenerator^9*/ mload(add(expmodsAndPoints, 0xc0)), PRIME) // expmods_and_points.points[64] = -(g^4102 * z). mstore(add(expmodsAndPoints, 0xa60), point) // point *= g^8. point := mulmod(point, /*traceGenerator^8*/ mload(add(expmodsAndPoints, 0xa0)), PRIME) // expmods_and_points.points[65] = -(g^4110 * z). mstore(add(expmodsAndPoints, 0xa80), point) // point *= g^8. point := mulmod(point, /*traceGenerator^8*/ mload(add(expmodsAndPoints, 0xa0)), PRIME) // expmods_and_points.points[66] = -(g^4118 * z). mstore(add(expmodsAndPoints, 0xaa0), point) // point *= g. point := mulmod(point, traceGenerator, PRIME) // expmods_and_points.points[67] = -(g^4119 * z). mstore(add(expmodsAndPoints, 0xac0), point) // point *= g^4041. point := mulmod(point, /*traceGenerator^4041*/ mload(add(expmodsAndPoints, 0x240)), PRIME) // expmods_and_points.points[68] = -(g^8160 * z). mstore(add(expmodsAndPoints, 0xae0), point) // point *= g^7. point := mulmod(point, /*traceGenerator^7*/ mload(add(expmodsAndPoints, 0x80)), PRIME) // expmods_and_points.points[69] = -(g^8167 * z). mstore(add(expmodsAndPoints, 0xb00), point) // point *= g^8. point := mulmod(point, /*traceGenerator^8*/ mload(add(expmodsAndPoints, 0xa0)), PRIME) // expmods_and_points.points[70] = -(g^8175 * z). mstore(add(expmodsAndPoints, 0xb20), point) // point *= g^2. point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME) // expmods_and_points.points[71] = -(g^8177 * z). mstore(add(expmodsAndPoints, 0xb40), point) // point *= g^4. point := mulmod(point, /*traceGenerator^4*/ mload(add(expmodsAndPoints, 0x40)), PRIME) // expmods_and_points.points[72] = -(g^8181 * z). mstore(add(expmodsAndPoints, 0xb60), point) // point *= g^2. point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME) // expmods_and_points.points[73] = -(g^8183 * z). mstore(add(expmodsAndPoints, 0xb80), point) // point *= g^2. point := mulmod(point, /*traceGenerator^2*/ mload(expmodsAndPoints), PRIME) // expmods_and_points.points[74] = -(g^8185 * z). mstore(add(expmodsAndPoints, 0xba0), point) // point *= g^4. point := mulmod(point, /*traceGenerator^4*/ mload(add(expmodsAndPoints, 0x40)), PRIME) // expmods_and_points.points[75] = -(g^8189 * z). mstore(add(expmodsAndPoints, 0xbc0), point) // point *= g^25. point := mulmod(point, /*traceGenerator^25*/ mload(add(expmodsAndPoints, 0x180)), PRIME) // expmods_and_points.points[76] = -(g^8214 * z). mstore(add(expmodsAndPoints, 0xbe0), point) } let evalPointsPtr := /*oodsEvalPoints*/ add(context, 0x6740) let evalPointsEndPtr := add(evalPointsPtr, mul(/*n_unique_queries*/ mload(add(context, 0x140)), 0x20)) let productsPtr := add(batchInverseArray, 0x20) let valuesPtr := add(add(batchInverseArray, 0x20), 0x1da00) let partialProduct := 1 let minusPointPow := sub(PRIME, mulmod(oodsPoint, oodsPoint, PRIME)) for {} lt(evalPointsPtr, evalPointsEndPtr) {evalPointsPtr := add(evalPointsPtr, 0x20)} { let evalPoint := mload(evalPointsPtr) // Shift evalPoint to evaluation domain coset. let shiftedEvalPoint := mulmod(evalPoint, evalCosetOffset_, PRIME) { // Calculate denominator for row 0: x - z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x260))) mstore(productsPtr, partialProduct) mstore(valuesPtr, denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 1: x - g * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x280))) mstore(add(productsPtr, 0x20), partialProduct) mstore(add(valuesPtr, 0x20), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 2: x - g^2 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x2a0))) mstore(add(productsPtr, 0x40), partialProduct) mstore(add(valuesPtr, 0x40), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 3: x - g^3 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x2c0))) mstore(add(productsPtr, 0x60), partialProduct) mstore(add(valuesPtr, 0x60), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4: x - g^4 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x2e0))) mstore(add(productsPtr, 0x80), partialProduct) mstore(add(valuesPtr, 0x80), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 5: x - g^5 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x300))) mstore(add(productsPtr, 0xa0), partialProduct) mstore(add(valuesPtr, 0xa0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 6: x - g^6 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x320))) mstore(add(productsPtr, 0xc0), partialProduct) mstore(add(valuesPtr, 0xc0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 7: x - g^7 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x340))) mstore(add(productsPtr, 0xe0), partialProduct) mstore(add(valuesPtr, 0xe0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8: x - g^8 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x360))) mstore(add(productsPtr, 0x100), partialProduct) mstore(add(valuesPtr, 0x100), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 9: x - g^9 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x380))) mstore(add(productsPtr, 0x120), partialProduct) mstore(add(valuesPtr, 0x120), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 10: x - g^10 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x3a0))) mstore(add(productsPtr, 0x140), partialProduct) mstore(add(valuesPtr, 0x140), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 11: x - g^11 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x3c0))) mstore(add(productsPtr, 0x160), partialProduct) mstore(add(valuesPtr, 0x160), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 12: x - g^12 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x3e0))) mstore(add(productsPtr, 0x180), partialProduct) mstore(add(valuesPtr, 0x180), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 13: x - g^13 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x400))) mstore(add(productsPtr, 0x1a0), partialProduct) mstore(add(valuesPtr, 0x1a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 14: x - g^14 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x420))) mstore(add(productsPtr, 0x1c0), partialProduct) mstore(add(valuesPtr, 0x1c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 15: x - g^15 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x440))) mstore(add(productsPtr, 0x1e0), partialProduct) mstore(add(valuesPtr, 0x1e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 16: x - g^16 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x460))) mstore(add(productsPtr, 0x200), partialProduct) mstore(add(valuesPtr, 0x200), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 19: x - g^19 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x480))) mstore(add(productsPtr, 0x220), partialProduct) mstore(add(valuesPtr, 0x220), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 21: x - g^21 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x4a0))) mstore(add(productsPtr, 0x240), partialProduct) mstore(add(valuesPtr, 0x240), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 22: x - g^22 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x4c0))) mstore(add(productsPtr, 0x260), partialProduct) mstore(add(valuesPtr, 0x260), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 23: x - g^23 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x4e0))) mstore(add(productsPtr, 0x280), partialProduct) mstore(add(valuesPtr, 0x280), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 24: x - g^24 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x500))) mstore(add(productsPtr, 0x2a0), partialProduct) mstore(add(valuesPtr, 0x2a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 25: x - g^25 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x520))) mstore(add(productsPtr, 0x2c0), partialProduct) mstore(add(valuesPtr, 0x2c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 28: x - g^28 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x540))) mstore(add(productsPtr, 0x2e0), partialProduct) mstore(add(valuesPtr, 0x2e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 30: x - g^30 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x560))) mstore(add(productsPtr, 0x300), partialProduct) mstore(add(valuesPtr, 0x300), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 31: x - g^31 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x580))) mstore(add(productsPtr, 0x320), partialProduct) mstore(add(valuesPtr, 0x320), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 38: x - g^38 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x5a0))) mstore(add(productsPtr, 0x340), partialProduct) mstore(add(valuesPtr, 0x340), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 39: x - g^39 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x5c0))) mstore(add(productsPtr, 0x360), partialProduct) mstore(add(valuesPtr, 0x360), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 44: x - g^44 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x5e0))) mstore(add(productsPtr, 0x380), partialProduct) mstore(add(valuesPtr, 0x380), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 55: x - g^55 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x600))) mstore(add(productsPtr, 0x3a0), partialProduct) mstore(add(valuesPtr, 0x3a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 60: x - g^60 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x620))) mstore(add(productsPtr, 0x3c0), partialProduct) mstore(add(valuesPtr, 0x3c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 63: x - g^63 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x640))) mstore(add(productsPtr, 0x3e0), partialProduct) mstore(add(valuesPtr, 0x3e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 70: x - g^70 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x660))) mstore(add(productsPtr, 0x400), partialProduct) mstore(add(valuesPtr, 0x400), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 71: x - g^71 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x680))) mstore(add(productsPtr, 0x420), partialProduct) mstore(add(valuesPtr, 0x420), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 76: x - g^76 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x6a0))) mstore(add(productsPtr, 0x440), partialProduct) mstore(add(valuesPtr, 0x440), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 86: x - g^86 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x6c0))) mstore(add(productsPtr, 0x460), partialProduct) mstore(add(valuesPtr, 0x460), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 87: x - g^87 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x6e0))) mstore(add(productsPtr, 0x480), partialProduct) mstore(add(valuesPtr, 0x480), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 92: x - g^92 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x700))) mstore(add(productsPtr, 0x4a0), partialProduct) mstore(add(valuesPtr, 0x4a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 102: x - g^102 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x720))) mstore(add(productsPtr, 0x4c0), partialProduct) mstore(add(valuesPtr, 0x4c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 103: x - g^103 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x740))) mstore(add(productsPtr, 0x4e0), partialProduct) mstore(add(valuesPtr, 0x4e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 108: x - g^108 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x760))) mstore(add(productsPtr, 0x500), partialProduct) mstore(add(valuesPtr, 0x500), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 124: x - g^124 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x780))) mstore(add(productsPtr, 0x520), partialProduct) mstore(add(valuesPtr, 0x520), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 134: x - g^134 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x7a0))) mstore(add(productsPtr, 0x540), partialProduct) mstore(add(valuesPtr, 0x540), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 135: x - g^135 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x7c0))) mstore(add(productsPtr, 0x560), partialProduct) mstore(add(valuesPtr, 0x560), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 150: x - g^150 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x7e0))) mstore(add(productsPtr, 0x580), partialProduct) mstore(add(valuesPtr, 0x580), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 151: x - g^151 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x800))) mstore(add(productsPtr, 0x5a0), partialProduct) mstore(add(valuesPtr, 0x5a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 167: x - g^167 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x820))) mstore(add(productsPtr, 0x5c0), partialProduct) mstore(add(valuesPtr, 0x5c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 199: x - g^199 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x840))) mstore(add(productsPtr, 0x5e0), partialProduct) mstore(add(valuesPtr, 0x5e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 230: x - g^230 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x860))) mstore(add(productsPtr, 0x600), partialProduct) mstore(add(valuesPtr, 0x600), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 255: x - g^255 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x880))) mstore(add(productsPtr, 0x620), partialProduct) mstore(add(valuesPtr, 0x620), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 256: x - g^256 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x8a0))) mstore(add(productsPtr, 0x640), partialProduct) mstore(add(valuesPtr, 0x640), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 263: x - g^263 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x8c0))) mstore(add(productsPtr, 0x660), partialProduct) mstore(add(valuesPtr, 0x660), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 295: x - g^295 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x8e0))) mstore(add(productsPtr, 0x680), partialProduct) mstore(add(valuesPtr, 0x680), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 327: x - g^327 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x900))) mstore(add(productsPtr, 0x6a0), partialProduct) mstore(add(valuesPtr, 0x6a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 391: x - g^391 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x920))) mstore(add(productsPtr, 0x6c0), partialProduct) mstore(add(valuesPtr, 0x6c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 406: x - g^406 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x940))) mstore(add(productsPtr, 0x6e0), partialProduct) mstore(add(valuesPtr, 0x6e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 423: x - g^423 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x960))) mstore(add(productsPtr, 0x700), partialProduct) mstore(add(valuesPtr, 0x700), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 455: x - g^455 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x980))) mstore(add(productsPtr, 0x720), partialProduct) mstore(add(valuesPtr, 0x720), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 511: x - g^511 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x9a0))) mstore(add(productsPtr, 0x740), partialProduct) mstore(add(valuesPtr, 0x740), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4081: x - g^4081 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x9c0))) mstore(add(productsPtr, 0x760), partialProduct) mstore(add(valuesPtr, 0x760), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4085: x - g^4085 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0x9e0))) mstore(add(productsPtr, 0x780), partialProduct) mstore(add(valuesPtr, 0x780), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4089: x - g^4089 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xa00))) mstore(add(productsPtr, 0x7a0), partialProduct) mstore(add(valuesPtr, 0x7a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4091: x - g^4091 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xa20))) mstore(add(productsPtr, 0x7c0), partialProduct) mstore(add(valuesPtr, 0x7c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4093: x - g^4093 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xa40))) mstore(add(productsPtr, 0x7e0), partialProduct) mstore(add(valuesPtr, 0x7e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4102: x - g^4102 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xa60))) mstore(add(productsPtr, 0x800), partialProduct) mstore(add(valuesPtr, 0x800), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4110: x - g^4110 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xa80))) mstore(add(productsPtr, 0x820), partialProduct) mstore(add(valuesPtr, 0x820), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4118: x - g^4118 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xaa0))) mstore(add(productsPtr, 0x840), partialProduct) mstore(add(valuesPtr, 0x840), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 4119: x - g^4119 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xac0))) mstore(add(productsPtr, 0x860), partialProduct) mstore(add(valuesPtr, 0x860), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8160: x - g^8160 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xae0))) mstore(add(productsPtr, 0x880), partialProduct) mstore(add(valuesPtr, 0x880), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8167: x - g^8167 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xb00))) mstore(add(productsPtr, 0x8a0), partialProduct) mstore(add(valuesPtr, 0x8a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8175: x - g^8175 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xb20))) mstore(add(productsPtr, 0x8c0), partialProduct) mstore(add(valuesPtr, 0x8c0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8177: x - g^8177 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xb40))) mstore(add(productsPtr, 0x8e0), partialProduct) mstore(add(valuesPtr, 0x8e0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8181: x - g^8181 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xb60))) mstore(add(productsPtr, 0x900), partialProduct) mstore(add(valuesPtr, 0x900), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8183: x - g^8183 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xb80))) mstore(add(productsPtr, 0x920), partialProduct) mstore(add(valuesPtr, 0x920), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8185: x - g^8185 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xba0))) mstore(add(productsPtr, 0x940), partialProduct) mstore(add(valuesPtr, 0x940), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8189: x - g^8189 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xbc0))) mstore(add(productsPtr, 0x960), partialProduct) mstore(add(valuesPtr, 0x960), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate denominator for row 8214: x - g^8214 * z. let denominator := add(shiftedEvalPoint, mload(add(expmodsAndPoints, 0xbe0))) mstore(add(productsPtr, 0x980), partialProduct) mstore(add(valuesPtr, 0x980), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } { // Calculate the denominator for the composition polynomial columns: x - z^2. let denominator := add(shiftedEvalPoint, minusPointPow) mstore(add(productsPtr, 0x9a0), partialProduct) mstore(add(valuesPtr, 0x9a0), denominator) partialProduct := mulmod(partialProduct, denominator, PRIME) } // Add evalPoint to batch inverse inputs. // inverse(evalPoint) is going to be used by FRI. mstore(add(productsPtr, 0x9c0), partialProduct) mstore(add(valuesPtr, 0x9c0), evalPoint) partialProduct := mulmod(partialProduct, evalPoint, PRIME) // Advance pointers. productsPtr := add(productsPtr, 0x9e0) valuesPtr := add(valuesPtr, 0x9e0) } let productsToValuesOffset := 0x1da00 let firstPartialProductPtr := add(batchInverseArray, 0x20) // Compute the inverse of the product. let prodInv := expmod(partialProduct, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := productsPtr // Loop in blocks of size 8 as much as possible: we can loop over a full block as long as // currentPartialProductPtr >= firstPartialProductPtr + 8*0x20, or equivalently, // currentPartialProductPtr > firstPartialProductPtr + 7*0x20. // We use the latter comparison since there is no >= evm opcode. let midPartialProductPtr := add(firstPartialProductPtr, 0xe0) for { } gt(currentPartialProductPtr, midPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } // Loop over the remainder. for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } } }
0x608060405234801561001057600080fd5b506060602060016000350102604051915080820160405280600083375060408051611da08082526203b4208201909252606091602082016203b4008038833901905050905061005f8282611621565b60007e4000000000000110000000000001210000000000000000000000000000000090507f08000000000000110000000000000000000000000000000000000000000000018184610dc0810160606101408301510281016183408301620119408401602089015b838510156116175760008888855109896151408901518b0382018b616d408b01518651090982019150896151608901518b0382018b616d608b01516020870151090982019150896151808901518b0382018b616d808b01516080870151090982019150896151a08901518b0382018b616da08b0151610100870151090982019150896151c08901518b0382018b616dc08b0151610180870151090982019150896151e08901518b0382018b616de08b01516102e0870151090982019150896152008901518b0382018b616e008b0151610380870151090982019150896152208901518b0382018b616e208b01516103c0870151090982019150896152408901518b0382018b616e408b0151610440870151090982019150896152608901518b0382018b616e608b01516104a0870151090982019150896152808901518b0382018b616e808b0151610500870151090982019150896152a08901518b0382018b616ea08b0151610520870151090982019150508888602086015109896152c08901518b0382018b616ec08b01518651090982019150896152e08901518b0382018b616ee08b01516020870151090982019150896153008901518b0382018b616f008b01516040870151090982019150896153208901518b0382018b616f208b01516060870151090982019150896153408901518b0382018b616f408b01516080870151090982019150896153608901518b0382018b616f608b015160a0870151090982019150896153808901518b0382018b616f808b015160c0870151090982019150896153a08901518b0382018b616fa08b015160e0870151090982019150896153c08901518b0382018b616fc08b0151610100870151090982019150896153e08901518b0382018b616fe08b0151610120870151090982019150896154008901518b0382018b6170008b0151610140870151090982019150896154208901518b0382018b6170208b0151610160870151090982019150896154408901518b0382018b6170408b0151610180870151090982019150896154608901518b0382018b6170608b01516101a0870151090982019150896154808901518b0382018b6170808b01516101c0870151090982019150896154a08901518b0382018b6170a08b01516101e0870151090982019150508888604086015109896154c08901518b0382018b6170c08b01518651090982019150896154e08901518b0382018b6170e08b01516020870151090982019150508888606086015109898a6155008a01518c0383018c6171008c01518751090983089150896155208901518b0382018b6171208b01516020870151090982019150896155408901518b0382018b6171408b0151610620870151090982019150896155608901518b0382018b6171608b0151610640870151090982019150896155808901518b0382018b6171808b0151610740870151090982019150508888608086015109896155a08901518b0382018b6171a08b01518651090982019150896155c08901518b0382018b6171c08b01516020870151090982019150896155e08901518b0382018b6171e08b0151610620870151090982019150896156008901518b0382018b6172008b015161064087015109098201915050888860a086015109896156208901518b0382018b6172208b0151865109098201915050888860c086015109896156408901518b0382018b6172408b01518651090982019150896156608901518b0382018b6172608b01516020870151090982019150896156808901518b0382018b6172808b015161064087015109098201915050888860e086015109896156a08901518b0382018b6172a08b01518651090982019150896156c08901518b0382018b6172c08b01516020870151090982019150896156e08901518b0382018b6172e08b0151610620870151090982019150896157008901518b0382018b6173008b0151610640870151090982019150896157208901518b0382018b6173208b015161074087015109098201915050888861010086015109896157408901518b0382018b6173408b01518651090982019150896157608901518b0382018b6173608b01516020870151090982019150896157808901518b0382018b6173808b0151610620870151090982019150896157a08901518b0382018b6173a08b015161064087015109098201915050888861012086015109896157c08901518b0382018b6173c08b0151865109098201915050888861014086015109896157e08901518b0382018b6173e08b01518651090982019150896158008901518b0382018b6174008b01516020870151090982019150896158208901518b0382018b6174208b015161064087015109098201915050888861016086015109896158408901518b0382018b6174408b01518651090982019150896158608901518b0382018b6174608b01516020870151090982019150896158808901518b0382018b6174808b0151610620870151090982019150896158a08901518b0382018b6174a08b0151610640870151090982019150896158c08901518b0382018b6174c08b015161074087015109098201915050888861018086015109898a6158e08a01518c0383018c6174e08c01518751090983089150896159008901518b0382018b6175008b01516020870151090982019150896159208901518b0382018b6175208b0151610620870151090982019150896159408901518b0382018b6175408b01516106408701510909820191505088886101a086015109896159608901518b0382018b6175608b015186510909820191505088886101c086015109896159808901518b0382018b6175808b01518651090982019150896159a08901518b0382018b6175a08b01516020870151090982019150896159c08901518b0382018b6175c08b01516106408701510909820191505088886101e086015109896159e08901518b0382018b6175e08b0151865109098201915089615a008901518b0382018b6176008b0151602087015109098201915089615a208901518b0382018b6176208b015161062087015109098201915089615a408901518b0382018b6176408b015161064087015109098201915089615a608901518b0382018b6176608b01516107408701510909820191505088886102008601510989615a808901518b0382018b6176808b0151865109098201915089615aa08901518b0382018b6176a08b0151602087015109098201915089615ac08901518b0382018b6176c08b015161062087015109098201915089615ae08901518b0382018b6176e08b01516106408701510909820191505088886102208601510989615b008901518b0382018b6177008b015186510909820191505088886102408601510989615b208901518b0382018b6177208b0151865109098201915089615b408901518b0382018b6177408b0151602087015109098201915089615b608901518b0382018b6177608b01516106408701510909820191505088886102608601510989615b808901518b0382018b6177808b0151865109098201915089615ba08901518b0382018b6177a08b0151602087015109098201915089615bc08901518b0382018b6177c08b0151604087015109098201915089615be08901518b0382018b6177e08b0151606087015109098201915089615c008901518b0382018b6178008b0151608087015109098201915089615c208901518b0382018b6178208b015160a087015109098201915089615c408901518b0382018b6178408b015160c087015109098201915089615c608901518b0382018b6178608b015160e087015109098201915089615c808901518b0382018b6178808b015161010087015109098201915089615ca08901518b0382018b6178a08b0151610120870151090982019150898a615cc08a01518c0383018c6178c08c015161018088015109098308915089615ce08901518b0382018b6178e08b01516101a087015109098201915089615d008901518b0382018b6179008b015161020087015109098201915089615d208901518b0382018b6179208b015161026087015109098201915089615d408901518b0382018b6179408b015161028087015109098201915089615d608901518b0382018b6179608b015161034087015109098201915089615d808901518b0382018b6179808b015161036087015109098201915089615da08901518b0382018b6179a08b015161040087015109098201915089615dc08901518b0382018b6179c08b015161042087015109098201915089615de08901518b0382018b6179e08b015161046087015109098201915089615e008901518b0382018b617a008b015161048087015109098201915089615e208901518b0382018b617a208b01516104c087015109098201915089615e408901518b0382018b617a408b01516104e087015109098201915089615e608901518b0382018b617a608b015161054087015109098201915089615e808901518b0382018b617a808b015161056087015109098201915089615ea08901518b0382018b617aa08b015161058087015109098201915089615ec08901518b0382018b617ac08b01516105a087015109098201915089615ee08901518b0382018b617ae08b01516105c087015109098201915089615f008901518b0382018b617b008b01516105e087015109098201915089615f208901518b0382018b617b208b015161060087015109098201915089615f408901518b0382018b617b408b015161066087015109098201915089615f608901518b0382018b617b608b015161068087015109098201915089615f808901518b0382018b617b808b01516106a087015109098201915089615fa08901518b0382018b617ba08b01516106c087015109098201915089615fc08901518b0382018b617bc08b01516106e087015109098201915089615fe08901518b0382018b617be08b0151610700870151090982019150896160008901518b0382018b617c008b0151610720870151090982019150896160208901518b0382018b617c208b0151610840870151090982019150896160408901518b0382018b617c408b0151610860870151090982019150896160608901518b0382018b617c608b015161098087015109098201915050888861028086015109896160808901518b0382018b617c808b01518651090982019150898a6160a08a01518c0383018c617ca08c01516020880151090983089150896160c08901518b0382018b617cc08b01516040870151090982019150896160e08901518b0382018b617ce08b015160608701510909820191505088886102a086015109896161008901518b0382018b617d008b01518651090982019150896161208901518b0382018b617d208b01516020870151090982019150896161408901518b0382018b617d408b01516040870151090982019150896161608901518b0382018b617d608b01516060870151090982019150896161808901518b0382018b617d808b01516080870151090982019150896161a08901518b0382018b617da08b015160a0870151090982019150896161c08901518b0382018b617dc08b015160c0870151090982019150896161e08901518b0382018b617de08b015160e0870151090982019150896162008901518b0382018b617e008b0151610100870151090982019150896162208901518b0382018b617e208b0151610120870151090982019150896162408901518b0382018b617e408b0151610140870151090982019150896162608901518b0382018b617e608b0151610160870151090982019150896162808901518b0382018b617e808b0151610180870151090982019150896162a08901518b0382018b617ea08b01516101a0870151090982019150896162c08901518b0382018b617ec08b01516101c0870151090982019150896162e08901518b0382018b617ee08b01516101e0870151090982019150896163008901518b0382018b617f008b0151610200870151090982019150896163208901518b0382018b617f208b0151610220870151090982019150896163408901518b0382018b617f408b0151610240870151090982019150896163608901518b0382018b617f608b0151610260870151090982019150896163808901518b0382018b617f808b0151610280870151090982019150896163a08901518b0382018b617fa08b01516102a0870151090982019150896163c08901518b0382018b617fc08b01516102c0870151090982019150896163e08901518b0382018b617fe08b0151610300870151090982019150896164008901518b0382018b6180008b0151610320870151090982019150896164208901518b0382018b6180208b0151610360870151090982019150896164408901518b0382018b6180408b01516103a0870151090982019150896164608901518b0382018b6180608b01516103e0870151090982019150898a6164808a01518c0383018c6180808c0151610760880151090983089150896164a08901518b0382018b6180a08b0151610780870151090982019150896164c08901518b0382018b6180c08b01516107a0870151090982019150896164e08901518b0382018b6180e08b01516107c0870151090982019150896165008901518b0382018b6181008b01516107e0870151090982019150896165208901518b0382018b6181208b0151610800870151090982019150896165408901518b0382018b6181408b0151610820870151090982019150896165608901518b0382018b6181608b01516108a0870151090982019150896165808901518b0382018b6181808b01516108c0870151090982019150896165a08901518b0382018b6181a08b01516108e0870151090982019150896165c08901518b0382018b6181c08b0151610900870151090982019150896165e08901518b0382018b6181e08b0151610920870151090982019150896166008901518b0382018b6182008b0151610940870151090982019150896166208901518b0382018b6182208b01516109608701510909820191505088886102c086015109896166408901518b0382018b6182408b01518651090982019150896166608901518b0382018b6182608b01516108808701510909820191505088886102e086015109896166808901518b0382018b6182808b01518651090982019150896166a08901518b0382018b6182a08b0151602087015109098201915050888861030086015109896166c08901518b0382018b6182c08b01518651090982019150896166e08901518b0382018b6182e08b0151604087015109098201915050610320840193508888845109896167008901518b0382018b6183008b01516109a0870151090982019150508888602085015109896167208901518b0382018b6183208b01516109a087015109099091018990066020870152506109c081015160408681019190915260609095019491909101906109e0016100c6565b611200610dc08701f35b600361162b6126e4565b611676565b600060405160208152602080820152602060408201528260608201528360808201528460a082015260208160c0836005600019fa61166d57600080fd5b51949350505050565b612b608401517f0800000000000011000000000000000000000000000000000000000000000001808283098352808284510960208401528082602085015109604084015280826040850151096060840181905283518291096080840152808260808501510960a0840152808260a08501510960c0840152808260c08501510960e0840152808260e08501510961010084018190526040840151829109610120840152808261012085015109610140840152808261014085015109610160840181905260a084015182910961018084015280610120840151610140850151096101a084015280826101a0850151096101c0840152806101808401516101a0850151096101e0840181905260a084015182910961020084015261179a81610df284611630565b6102208401526117ad81610fc984611630565b610240840152612b808601518082038061026086015282848209905080610280860152828482099050806102a0860152828482099050806102c0860152828482099050806102e08601528284820990508061030086015282848209905080610320860152828482099050806103408601528284820990508061036086015282848209905080610380860152828482099050806103a0860152828482099050806103c0860152828482099050806103e086015282848209905080610400860152828482099050806104208601528284820990508061044086015282848209905080610460860152826020860151820990508061048086015282855182099050806104a0860152828482099050806104c0860152828482099050806104e08601528284820990508061050086015282848209905080610520860152826020860151820990508061054086015282855182099050806105608601528284820990508061058086015282608086015182099050806105a0860152828482099050806105c086015282606086015182099050806105e08601528261010086015182099050806106008601528260608601518209905080610620860152826020860151820990508061064086015282608086015182099050806106608601528284820990508061068086015282606086015182099050806106a08601528260e086015182099050806106c0860152828482099050806106e086015282606086015182099050806107008601528260e086015182099050806107208601528284820990508061074086015282606086015182099050806107608601528261014086015182099050806107808601528260e086015182099050806107a0860152828482099050806107c08601528261012086015182099050806107e086015282848209905080610800860152826101408601518209905080610820860152826101c08601518209905080610840860152826101a08601518209905080610860860152826101808601518209905080610880860152828482099050806108a086015282608086015182099050806108c0860152826101c086015182099050806108e0860152826101c08601518209905080610900860152826102008601518209905080610920860152826101208601518209905080610940860152826101608601518209905080610960860152826101c08601518209905080610980860152826101e086015182099050806109a08601528261022086015182099050806109c086015282604086015182099050806109e08601528260408601518209905080610a008601528285518209905080610a208601528285518209905080610a408601528260c08601518209905080610a608601528260a08601518209905080610a808601528260a08601518209905080610aa086015282848209905080610ac0860152826102408601518209905080610ae08601528260808601518209905080610b008601528260a08601518209905080610b208601528285518209905080610b408601528260408601518209905080610b608601528285518209905080610b808601528285518209905080610ba08601528260408601518209905080610bc0860152826101808601518209905080610be08601525061674087016020610140890151028101602088016201da0060208a010160018686870987035b84861015612576578551888c82096102608c015181018487528086528a8186099450506102808c015181018460208801528060208701528a8186099450506102a08c015181018460408801528060408701528a8186099450506102c08c015181018460608801528060608701528a8186099450506102e08c015181018460808801528060808701528a8186099450506103008c015181018460a08801528060a08701528a8186099450506103208c015181018460c08801528060c08701528a8186099450506103408c015181018460e08801528060e08701528a8186099450506103608c0151810184610100880152806101008701528a8186099450506103808c0151810184610120880152806101208701528a8186099450506103a08c0151810184610140880152806101408701528a8186099450506103c08c0151810184610160880152806101608701528a8186099450506103e08c0151810184610180880152806101808701528a8186099450506104008c01518101846101a0880152806101a08701528a8186099450506104208c01518101846101c0880152806101c08701528a8186099450506104408c01518101846101e0880152806101e08701528a8186099450506104608c0151810184610200880152806102008701528a8186099450506104808c0151810184610220880152806102208701528a8186099450506104a08c0151810184610240880152806102408701528a8186099450506104c08c0151810184610260880152806102608701528a8186099450506104e08c0151810184610280880152806102808701528a8186099450506105008c01518101846102a0880152806102a08701528a8186099450506105208c01518101846102c0880152806102c08701528a8186099450506105408c01518101846102e0880152806102e08701528a8186099450506105608c0151810184610300880152806103008701528a8186099450506105808c0151810184610320880152806103208701528a8186099450506105a08c0151810184610340880152806103408701528a8186099450506105c08c0151810184610360880152806103608701528a8186099450506105e08c0151810184610380880152806103808701528a8186099450506106008c01518101846103a0880152806103a08701528a8186099450506106208c01518101846103c0880152806103c08701528a8186099450506106408c01518101846103e0880152806103e08701528a8186099450506106608c0151810184610400880152806104008701528a8186099450506106808c0151810184610420880152806104208701528a8186099450506106a08c0151810184610440880152806104408701528a8186099450506106c08c0151810184610460880152806104608701528a8186099450506106e08c0151810184610480880152806104808701528a8186099450506107008c01518101846104a0880152806104a08701528a8186099450506107208c01518101846104c0880152806104c08701528a8186099450506107408c01518101846104e0880152806104e08701528a8186099450506107608c0151810184610500880152806105008701528a8186099450506107808c0151810184610520880152806105208701528a8186099450506107a08c0151810184610540880152806105408701528a8186099450506107c08c0151810184610560880152806105608701528a8186099450506107e08c0151810184610580880152806105808701528a8186099450506108008c01518101846105a0880152806105a08701528a8186099450506108208c01518101846105c0880152806105c08701528a8186099450506108408c01518101846105e0880152806105e08701528a8186099450506108608c0151810184610600880152806106008701528a8186099450506108808c0151810184610620880152806106208701528a8186099450506108a08c0151810184610640880152806106408701528a8186099450506108c08c0151810184610660880152806106608701528a8186099450506108e08c0151810184610680880152806106808701528a8186099450506109008c01518101846106a0880152806106a08701528a8186099450506109208c01518101846106c0880152806106c08701528a8186099450506109408c01518101846106e0880152806106e08701528a8186099450506109608c0151810184610700880152806107008701528a8186099450506109808c0151810184610720880152806107208701528a8186099450506109a08c0151810184610740880152806107408701528a8186099450506109c08c0151810184610760880152806107608701528a8186099450506109e08c0151810184610780880152806107808701528a818609945050610a008c01518101846107a0880152806107a08701528a818609945050610a208c01518101846107c0880152806107c08701528a818609945050610a408c01518101846107e0880152806107e08701528a818609945050610a608c0151810184610800880152806108008701528a818609945050610a808c0151810184610820880152806108208701528a818609945050610aa08c0151810184610840880152806108408701528a818609945050610ac08c0151810184610860880152806108608701528a818609945050610ae08c0151810184610880880152806108808701528a818609945050610b008c01518101846108a0880152806108a08701528a818609945050610b208c01518101846108c0880152806108c08701528a818609945050610b408c01518101846108e0880152806108e08701528a818609945050610b608c0151810184610900880152806109008701528a818609945050610b808c0151810184610920880152806109208701528a818609945050610ba08c0151810184610940880152806109408701528a818609945050610bc08c0151810184610960880152806109608701528a818609945050610be08c0151810184610980880152806109808701528a818609945050828101846109a0880152806109a08701528a818609945050836109c0870152816109c08601528982850993506109e0860195506109e0850194505050602086019550611c7e565b6201da0060208d0161258c8a60028c0386611630565b806125e9577f08c379a0000000000000000000000000000000000000000000000000000000006000526020600452601e6024527f426174636820696e76657273652070726f64756374206973207a65726f2e000060445260626000fd5b8660e083015b808211156126ac576020820391508c8383510982528c85830151840992506020820391508c8383510982528c85830151840992506020820391508c8383510982528c85830151840992506020820391508c8383510982528c85830151840992506020820391508c8383510982528c85830151840992506020820391508c8383510982528c85830151840992506020820391508c8383510982528c85830151840992506020820391508c8383510982528c85830151840992506125ef565b5b838211156126d0576020820391508c8383510982528c85830151840992506126ad565b505050505050505050505050505050505050565b60405180610c000160405280606090602082028038833950919291505056fea265627a7a723158203a549a5a8034c32e98a1dfd2040c25a44585a0af019e6d94f4afc76b3200ada164736f6c634300050f0032
[ 38 ]
0x510a0581795a8e985af080388a8fae37793dd06c
pragma solidity 0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract unus is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function unus( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a723058204092f72c34ef67d199c0cb262d0cbdfba2830d0e726cfcc7a6bbb45e510a0c670029
[ 38 ]
0x515e39f12590a94B102903363336AF9761ebF621
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Migrations { address public owner; // solhint-disable-next-line var-name-mixedcase uint public last_completed_migration; constructor() public { owner = msg.sender; } modifier restricted() { if (msg.sender == owner) _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address newAddress) public restricted { Migrations upgraded = Migrations(newAddress); upgraded.setCompleted(last_completed_migration); } } interface IForwarder { struct ForwardRequest { address from; address to; uint256 value; uint256 gas; uint256 nonce; bytes data; } function getNonce(address from) external view returns(uint256); /** * verify the transaction would execute. * validate the signature and the nonce of the request. * revert if either signature or nonce are incorrect. */ function verify( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external view; /** * execute a transaction * @param forwardRequest - all transaction parameters * @param domainSeparator - domain used when signing this request * @param requestTypeHash - request type used when signing this request. * @param suffixData - the extension data used when signing this request. * @param signature - signature to validate. * * the transaction is verified, and then executed. * the success and ret of "call" are returned. * This method would revert only verification errors. target errors * are reported using the returned "success" and ret string */ function execute( ForwardRequest calldata forwardRequest, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata signature ) external payable returns (bool success, bytes memory ret); /** * Register a new Request typehash. * @param typeName - the name of the request type. * @param typeSuffix - anything after the generic params can be empty string (if no extra fields are needed) * if it does contain a value, then a comma is added first. */ function registerRequestType(string calldata typeName, string calldata typeSuffix) external; /** * Register a new domain separator. * The domain separator must have the following fields: name,version,chainId, verifyingContract. * the chainId is the current network's chainId, and the verifyingContract is this forwarder. * This method is given the domain name and version to create and register the domain separator value. * @param name the domain's display name * @param version the domain/protocol version */ function registerDomainSeparator(string calldata name, string calldata version) external; } contract TestForwarder { function callExecute(Forwarder forwarder, Forwarder.ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes memory suffixData, bytes memory sig) public payable { (bool success, bytes memory error) = forwarder.execute{value:msg.value}(req, domainSeparator, requestTypeHash, suffixData, sig); emit Result(success, success ? "" : this.decodeErrorMessage(error)); } event Result(bool success, string error); function decodeErrorMessage(bytes calldata ret) external pure returns (string memory message) { //decode evert string: assume it has a standard Error(string) signature: simply skip the (selector,offset,length) fields if ( ret.length>4+32+32 ) { return abi.decode(ret[4:], (string)); } //unknown buffer. return as-is return string(ret); } function getChainId() public pure returns (uint256 id){ /* solhint-disable-next-line no-inline-assembly */ assembly { id := chainid() } } } interface GsnTypes { struct RelayData { uint256 gasPrice; uint256 pctRelayFee; uint256 baseRelayFee; address relayWorker; address paymaster; bytes paymasterData; uint256 clientId; address forwarder; } //note: must start with the ForwardRequest to be an extension of the generic forwarder struct RelayRequest { IForwarder.ForwardRequest request; RelayData relayData; } } interface IKnowForwarderAddress { /** * return the forwarder we trust to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function getTrustedForwarder() external view returns(address); } interface IPaymaster { /** * @param acceptanceBudget - * Paymaster expected gas budget to accept (or reject) a request * This a gas required by any calculations that might need to reject the * transaction, by preRelayedCall, forwarder and recipient. * See value in BasePaymaster.PAYMASTER_ACCEPTANCE_BUDGET * Transaction that gets rejected above that gas usage is on the paymaster's expense. * As long this value is above preRelayedCallGasLimit (see defaults in BasePaymaster), the * Paymaster is guaranteed it will never pay for rejected transactions. * If this value is below preRelayedCallGasLimt, it might might make Paymaster open to a "griefing" attack. * * Specifying value too high might make the call rejected by some relayers. * * From a Relay's point of view, this is the highest gas value a paymaster might "grief" the relay, * since the paymaster will pay anything above that (regardless if the tx reverts) * * @param preRelayedCallGasLimit - the max gas usage of preRelayedCall. any revert (including OOG) * of preRelayedCall is a reject by the paymaster. * as long as acceptanceBudget is above preRelayedCallGasLimit, any such revert (including OOG) * is not payed by the paymaster. * @param postRelayedCallGasLimit - the max gas usage of postRelayedCall. * note that an OOG will revert the transaction, but the paymaster already committed to pay, * so the relay will get compensated, at the expense of the paymaster */ struct GasLimits { uint256 acceptanceBudget; uint256 preRelayedCallGasLimit; uint256 postRelayedCallGasLimit; } /** * Return the GasLimits constants used by the Paymaster. */ function getGasLimits() external view returns ( GasLimits memory limits ); function trustedForwarder() external view returns (IForwarder); /** * return the relayHub of this contract. */ function getHubAddr() external view returns (address); /** * Can be used to determine if the contract can pay for incoming calls before making any. * @return the paymaster's deposit in the RelayHub. */ function getRelayHubDeposit() external view returns (uint256); /** * Called by Relay (and RelayHub), to validate if the paymaster agrees to pay for this call. * * MUST be protected with relayHubOnly() in case it modifies state. * * The Paymaster rejects by the following "revert" operations * - preRelayedCall() method reverts * - the forwarder reverts because of nonce or signature error * - the paymaster returned "rejectOnRecipientRevert", and the recipient contract reverted. * In any of the above cases, all paymaster calls (and recipient call) are reverted. * In any other case, the paymaster agrees to pay for the gas cost of the transaction (note * that this includes also postRelayedCall revert) * * The rejectOnRecipientRevert flag means the Paymaster "delegate" the rejection to the recipient * code. It also means the Paymaster trust the recipient to reject fast: both preRelayedCall, * forwarder check and receipient checks must fit into the GasLimits.acceptanceBudget, * otherwise the TX is paid by the Paymaster. * * @param relayRequest - the full relay request structure * @param signature - user's EIP712-compatible signature of the {@link relayRequest}. * Note that in most cases the paymaster shouldn't try use it at all. It is always checked * by the forwarder immediately after preRelayedCall returns. * @param approvalData - extra dapp-specific data (e.g. signature from trusted party) * @param maxPossibleGas - based on values returned from {@link getGasLimits}, * the RelayHub will calculate the maximum possible amount of gas the user may be charged for. * In order to convert this value to wei, the Paymaster has to call "relayHub.calculateCharge()" * return: * a context to be passed to postRelayedCall * rejectOnRecipientRevert - TRUE if paymaster want to reject the TX if the recipient reverts. * FALSE means that rejects by the recipient will be completed on chain, and paid by the paymaster. * (note that in the latter case, the preRelayedCall and postRelayedCall are not reverted). */ function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external returns (bytes memory context, bool rejectOnRecipientRevert); /** * This method is called after the actual relayed function call. * It may be used to record the transaction (e.g. charge the caller by some contract logic) for this call. * * MUST be protected with relayHubOnly() in case it modifies state. * * @param context - the call context, as returned by the preRelayedCall * @param success - true if the relayed call succeeded, false if it reverted * @param gasUseWithoutPost - the actual amount of gas used by the entire transaction, EXCEPT * the gas used by the postRelayedCall itself. * @param relayData - the relay params of the request. can be used by relayHub.calculateCharge() * * Revert in this functions causes a revert of the client's relayed call (and preRelayedCall(), but the Paymaster * is still committed to pay the relay for the entire transaction. */ function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external; function versionPaymaster() external view returns (string memory); } interface IPenalizer { struct Transaction { uint256 nonce; uint256 gasPrice; uint256 gasLimit; address to; uint256 value; bytes data; } function penalizeRepeatedNonce( bytes calldata unsignedTx1, bytes calldata signature1, bytes calldata unsignedTx2, bytes calldata signature2, IRelayHub hub ) external; function penalizeIllegalTransaction( bytes calldata unsignedTx, bytes calldata signature, IRelayHub hub ) external; function versionPenalizer() external view returns (string memory); } interface IRelayHub { /// Emitted when a relay server registers or updates its details /// Looking at these events lets a client discover relay servers event RelayServerRegistered( address indexed relayManager, uint256 baseRelayFee, uint256 pctRelayFee, string relayUrl); /// Emitted when relays are added by a relayManager event RelayWorkersAdded( address indexed relayManager, address[] newRelayWorkers, uint256 workersCount ); // Emitted when an account withdraws funds from RelayHub. event Withdrawn( address indexed account, address indexed dest, uint256 amount ); // Emitted when depositFor is called, including the amount and account that was funded. event Deposited( address indexed paymaster, address indexed from, uint256 amount ); /// Emitted when an attempt to relay a call fails and Paymaster does not accept the transaction. /// The actual relayed call was not executed, and the recipient not charged. /// @param reason contains a revert reason returned from preRelayedCall or forwarder. event TransactionRejectedByPaymaster( address indexed relayManager, address indexed paymaster, address indexed from, address to, address relayWorker, bytes4 selector, uint256 innerGasUsed, bytes reason); // Emitted when a transaction is relayed. Note that the actual encoded function might be reverted: this will be // indicated in the status field. // Useful when monitoring a relay's operation and relayed calls to a contract. // Charge is the ether value deducted from the recipient's balance, paid to the relay's manager. event TransactionRelayed( address indexed relayManager, address indexed relayWorker, address indexed from, address to, address paymaster, bytes4 selector, RelayCallStatus status, uint256 charge); event TransactionResult( RelayCallStatus status, bytes returnValue ); event Penalized( address indexed relayWorker, address sender, uint256 reward ); /// Reason error codes for the TransactionRelayed event /// @param OK - the transaction was successfully relayed and execution successful - never included in the event /// @param RelayedCallFailed - the transaction was relayed, but the relayed call failed /// @param RejectedByPreRelayed - the transaction was not relayed due to preRelatedCall reverting /// @param RejectedByForwarder - the transaction was not relayed due to forwarder check (signature,nonce) /// @param PostRelayedFailed - the transaction was relayed and reverted due to postRelatedCall reverting /// @param PaymasterBalanceChanged - the transaction was relayed and reverted due to the paymaster balance change enum RelayCallStatus { OK, RelayedCallFailed, RejectedByPreRelayed, RejectedByForwarder, RejectedByRecipientRevert, PostRelayedFailed, PaymasterBalanceChanged } /// Add new worker addresses controlled by sender who must be a staked Relay Manager address. /// Emits a RelayWorkersAdded event. /// This function can be called multiple times, emitting new events function addRelayWorkers(address[] calldata newRelayWorkers) external; function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external; // Balance management // Deposits ether for a contract, so that it can receive (and pay for) relayed transactions. Unused balance can only // be withdrawn by the contract itself, by calling withdraw. // Emits a Deposited event. function depositFor(address target) external payable; // Withdraws from an account's balance, sending it back to it. Relay managers call this to retrieve their revenue, and // contracts can also use it to reduce their funding. // Emits a Withdrawn event. function withdraw(uint256 amount, address payable dest) external; // Relaying /// Relays a transaction. For this to succeed, multiple conditions must be met: /// - Paymaster's "acceptRelayCall" method must succeed and not revert /// - the sender must be a registered Relay Worker that the user signed /// - the transaction's gas price must be equal or larger than the one that was signed by the sender /// - the transaction must have enough gas to run all internal transactions if they use all gas available to them /// - the Paymaster must have enough balance to pay the Relay Worker for the scenario when all gas is spent /// /// If all conditions are met, the call will be relayed and the recipient charged. /// /// Arguments: /// @param relayRequest - all details of the requested relayed call /// @param signature - client's EIP-712 signature over the relayRequest struct /// @param approvalData: dapp-specific data forwarded to preRelayedCall. /// This value is *not* verified by the Hub. For example, it can be used to pass a signature to the Paymaster /// @param externalGasLimit - the value passed as gasLimit to the transaction. /// /// Emits a TransactionRelayed event. function relayCall( uint paymasterMaxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external returns (bool paymasterAccepted, bytes memory returnValue); function penalize(address relayWorker, address payable beneficiary) external; /// The fee is expressed as a base fee in wei plus percentage on actual charge. /// E.g. a value of 40 stands for a 40% fee, so the recipient will be /// charged for 1.4 times the spent amount. function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) external view returns (uint256); /* getters */ /// Returns the stake manager of this RelayHub. function stakeManager() external view returns(IStakeManager); function penalizer() external view returns(address); /// Returns an account's deposits. It can be either a deposit of a paymaster, or a revenue of a relay manager. function balanceOf(address target) external view returns (uint256); // Minimum stake a relay can have. An attack to the network will never cost less than half this value. function minimumStake() external view returns (uint256); // Minimum unstake delay blocks of a relay manager's stake on the StakeManager function minimumUnstakeDelay() external view returns (uint256); // Maximum funds that can be deposited at once. Prevents user error by disallowing large deposits. function maximumRecipientDeposit() external view returns (uint256); //gas overhead to calculate gasUseWithoutPost function postOverhead() external view returns (uint256); // Gas set aside for all relayCall() instructions to prevent unexpected out-of-gas exceptions function gasReserve() external view returns (uint256); // maximum number of worker account allowed per manager function maxWorkerCount() external view returns (uint256); function workerToManager(address worker) external view returns(address); function workerCount(address manager) external view returns(uint256); function isRelayManagerStaked(address relayManager) external view returns(bool); /** * @dev the total gas overhead of relayCall(), before the first gasleft() and after the last gasleft(). * Assume that relay has non-zero balance (costs 15'000 more otherwise). */ // Gas cost of all relayCall() instructions after actual 'calculateCharge()' function gasOverhead() external view returns (uint256); function versionHub() external view returns (string memory); } abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } interface IStakeManager { /// Emitted when a stake or unstakeDelay are initialized or increased event StakeAdded( address indexed relayManager, address indexed owner, uint256 stake, uint256 unstakeDelay ); /// Emitted once a stake is scheduled for withdrawal event StakeUnlocked( address indexed relayManager, address indexed owner, uint256 withdrawBlock ); /// Emitted when owner withdraws relayManager funds event StakeWithdrawn( address indexed relayManager, address indexed owner, uint256 amount ); /// Emitted when an authorized Relay Hub penalizes a relayManager event StakePenalized( address indexed relayManager, address indexed beneficiary, uint256 reward ); event HubAuthorized( address indexed relayManager, address indexed relayHub ); event HubUnauthorized( address indexed relayManager, address indexed relayHub, uint256 removalBlock ); /// @param stake - amount of ether staked for this relay /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' /// @param withdrawBlock - first block number 'withdraw' will be callable, or zero if the unlock has not been called /// @param owner - address that receives revenue and manages relayManager's stake struct StakeInfo { uint256 stake; uint256 unstakeDelay; uint256 withdrawBlock; address payable owner; } struct RelayHubInfo { uint256 removalBlock; } /// Put a stake for a relayManager and set its unstake delay. /// If the entry does not exist, it is created, and the caller of this function becomes its owner. /// If the entry already exists, only the owner can call this function. /// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' function stakeForAddress(address relayManager, uint256 unstakeDelay) external payable; function unlockStake(address relayManager) external; function withdrawStake(address relayManager) external; function authorizeHubByOwner(address relayManager, address relayHub) external; function authorizeHubByManager(address relayHub) external; function unauthorizeHubByOwner(address relayManager, address relayHub) external; function unauthorizeHubByManager(address relayHub) external; function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay) external view returns (bool); /// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way. /// @param relayManager - entry to penalize /// @param beneficiary - address that receives half of the penalty amount /// @param amount - amount to withdraw from stake function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external; function getStakeInfo(address relayManager) external view returns (StakeInfo memory stakeInfo); function versionSM() external view returns (string memory); } interface IVersionRegistry { //event emitted whenever a version is added event VersionAdded(bytes32 indexed id, bytes32 version, string value, uint time); //event emitted whenever a version is canceled event VersionCanceled(bytes32 indexed id, bytes32 version, string reason); /** * add a version * @param id the object-id to add a version (32-byte string) * @param version the new version to add (32-byte string) * @param value value to attach to this version */ function addVersion(bytes32 id, bytes32 version, string calldata value) external; /** * cancel a version. */ function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external; } contract TestRelayWorkerContract { function relayCall( IRelayHub hub, uint maxAcceptanceBudget, GsnTypes.RelayRequest memory relayRequest, bytes memory signature, uint externalGasLimit) public { hub.relayCall{gas:externalGasLimit}(maxAcceptanceBudget, relayRequest, signature, "", externalGasLimit); } } contract TestUtil { function libRelayRequestName() public pure returns (string memory) { return GsnEip712Library.RELAY_REQUEST_NAME; } function libRelayRequestType() public pure returns (string memory) { return string(GsnEip712Library.RELAY_REQUEST_TYPE); } function libRelayRequestTypeHash() public pure returns (bytes32) { return GsnEip712Library.RELAY_REQUEST_TYPEHASH; } function libRelayRequestSuffix() public pure returns (string memory) { return GsnEip712Library.RELAY_REQUEST_SUFFIX; } //helpers for test to call the library funcs: function callForwarderVerify( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature ) external view { GsnEip712Library.verify(relayRequest, signature); } function callForwarderVerifyAndCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature ) external returns ( bool success, bytes memory ret ) { bool forwarderSuccess; (forwarderSuccess, success, ret) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess) { GsnUtils.revertWithData(ret); } emit Called(success, success == false ? ret : bytes("")); } event Called(bool success, bytes error); function splitRequest( GsnTypes.RelayRequest calldata relayRequest ) external pure returns ( IForwarder.ForwardRequest memory forwardRequest, bytes32 typeHash, bytes memory suffixData ) { (forwardRequest, suffixData) = GsnEip712Library.splitRequest(relayRequest); typeHash = GsnEip712Library.RELAY_REQUEST_TYPEHASH; } function libDomainSeparator(address forwarder) public pure returns (bytes32) { return GsnEip712Library.domainSeparator(forwarder); } function libGetChainID() public pure returns (uint256) { return GsnEip712Library.getChainID(); } } contract TestVersions { // stub for ContractInteractor "init" to succeed function stakeManager() external view returns (address) { return address(this); } function versionHub() external pure returns (string memory) { return "3.0.0"; } } library GsnEip712Library { // maximum length of return value/revert reason for 'execute' method. Will truncate result if exceeded. uint256 private constant MAX_RETURN_SIZE = 1024; //copied from Forwarder (can't reference string constants even from another library) string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data"; bytes public constant RELAYDATA_TYPE = "RelayData(uint256 gasPrice,uint256 pctRelayFee,uint256 baseRelayFee,address relayWorker,address paymaster,address forwarder,bytes paymasterData,uint256 clientId)"; string public constant RELAY_REQUEST_NAME = "RelayRequest"; string public constant RELAY_REQUEST_SUFFIX = string(abi.encodePacked("RelayData relayData)", RELAYDATA_TYPE)); bytes public constant RELAY_REQUEST_TYPE = abi.encodePacked( RELAY_REQUEST_NAME,"(",GENERIC_PARAMS,",", RELAY_REQUEST_SUFFIX); bytes32 public constant RELAYDATA_TYPEHASH = keccak256(RELAYDATA_TYPE); bytes32 public constant RELAY_REQUEST_TYPEHASH = keccak256(RELAY_REQUEST_TYPE); struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); function splitRequest( GsnTypes.RelayRequest calldata req ) internal pure returns ( IForwarder.ForwardRequest memory forwardRequest, bytes memory suffixData ) { forwardRequest = IForwarder.ForwardRequest( req.request.from, req.request.to, req.request.value, req.request.gas, req.request.nonce, req.request.data ); suffixData = abi.encode( hashRelayData(req.relayData)); } //verify that the recipient trusts the given forwarder // MUST be called by paymaster function verifyForwarderTrusted(GsnTypes.RelayRequest calldata relayRequest) internal view { (bool success, bytes memory ret) = relayRequest.request.to.staticcall( abi.encodeWithSelector( IRelayRecipient.isTrustedForwarder.selector, relayRequest.relayData.forwarder ) ); require(success, "isTrustedForwarder reverted"); require(ret.length == 32, "isTrustedForwarder returned invalid response"); require(abi.decode(ret, (bool)), "invalid forwarder for recipient"); } function verifySignature(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view { (IForwarder.ForwardRequest memory forwardRequest, bytes memory suffixData) = splitRequest(relayRequest); bytes32 domainSeparator = domainSeparator(relayRequest.relayData.forwarder); IForwarder forwarder = IForwarder(payable(relayRequest.relayData.forwarder)); forwarder.verify(forwardRequest, domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature); } function verify(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal view { verifyForwarderTrusted(relayRequest); verifySignature(relayRequest, signature); } function execute(GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature) internal returns (bool forwarderSuccess, bool callSuccess, bytes memory ret) { (IForwarder.ForwardRequest memory forwardRequest, bytes memory suffixData) = splitRequest(relayRequest); bytes32 domainSeparator = domainSeparator(relayRequest.relayData.forwarder); /* solhint-disable-next-line avoid-low-level-calls */ (forwarderSuccess, ret) = relayRequest.relayData.forwarder.call( abi.encodeWithSelector(IForwarder.execute.selector, forwardRequest, domainSeparator, RELAY_REQUEST_TYPEHASH, suffixData, signature )); if ( forwarderSuccess ) { //decode return value of execute: (callSuccess, ret) = abi.decode(ret, (bool, bytes)); } truncateInPlace(ret); } //truncate the given parameter (in-place) if its length is above the given maximum length // do nothing otherwise. //NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter. function truncateInPlace(bytes memory data) internal pure { MinLibBytes.truncateInPlace(data, MAX_RETURN_SIZE); } function domainSeparator(address forwarder) internal pure returns (bytes32) { return hashDomain(EIP712Domain({ name : "GSN Relayed Transaction", version : "2", chainId : getChainID(), verifyingContract : forwarder })); } function getChainID() internal pure returns (uint256 id) { /* solhint-disable no-inline-assembly */ assembly { id := chainid() } } function hashDomain(EIP712Domain memory req) internal pure returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(req.name)), keccak256(bytes(req.version)), req.chainId, req.verifyingContract)); } function hashRelayData(GsnTypes.RelayData calldata req) internal pure returns (bytes32) { return keccak256(abi.encode( RELAYDATA_TYPEHASH, req.gasPrice, req.pctRelayFee, req.baseRelayFee, req.relayWorker, req.paymaster, req.forwarder, keccak256(req.paymasterData), req.clientId )); } } library GsnUtils { /** * extract method sig from encoded function call */ function getMethodSig(bytes memory msgData) internal pure returns (bytes4) { return MinLibBytes.readBytes4(msgData, 0); } /** * extract parameter from encoded-function block. * see: https://solidity.readthedocs.io/en/develop/abi-spec.html#formal-specification-of-the-encoding * the return value should be casted to the right type (uintXXX/bytesXXX/address/bool/enum) */ function getParam(bytes memory msgData, uint index) internal pure returns (uint) { return MinLibBytes.readUint256(msgData, 4 + index * 32); } //re-throw revert with the same revert data. function revertWithData(bytes memory data) internal pure { assembly { revert(add(data,32), mload(data)) } } } library MinLibBytes { //truncate the given parameter (in-place) if its length is above the given maximum length // do nothing otherwise. //NOTE: solidity warns unless the method is marked "pure", but it DOES modify its parameter. function truncateInPlace(bytes memory data, uint256 maxlen) internal pure { if (data.length > maxlen) { assembly { mstore(data, maxlen) } } } /// @dev Reads an address from a position in a byte array. /// @param b Byte array containing an address. /// @param index Index in byte array of address. /// @return result address from byte array. function readAddress( bytes memory b, uint256 index ) internal pure returns (address result) { require (b.length >= index + 20, "readAddress: data too short"); // Add offset to index: // 1. Arrays are prefixed by 32-byte length parameter (add 32 to index) // 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index) index += 20; // Read address from array memory assembly { // 1. Add index to address of bytes array // 2. Load 32-byte word from memory // 3. Apply 20-byte mask to obtain address result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff) } return result; } function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require(b.length >= index + 32, "readBytes32: data too short" ); // Read the bytes32 from array memory assembly { result := mload(add(b, add(index,32))) } return result; } /// @dev Reads a uint256 value from a position in a byte array. /// @param b Byte array containing a uint256 value. /// @param index Index in byte array of uint256 value. /// @return result uint256 value from byte array. function readUint256( bytes memory b, uint256 index ) internal pure returns (uint256 result) { result = uint256(readBytes32(b, index)); return result; } function readBytes4( bytes memory b, uint256 index ) internal pure returns (bytes4 result) { require(b.length >= index + 4, "readBytes4: data too short"); // Read the bytes4 from array memory assembly { result := mload(add(b, add(index,32))) // Solidity does not require us to clean the trailing bytes. // We do it anyway result := and(result, 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000) } return result; } } library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } using RLPReader for bytes; using RLPReader for uint; using RLPReader for RLPReader.RLPItem; // helper function to decode rlp encoded ethereum transaction /* * @param rawTransaction RLP encoded ethereum transaction * @return tuple (nonce,gasPrice,gasLimit,to,value,data) */ function decodeTransaction(bytes memory rawTransaction) internal pure returns (uint, uint, uint, address, uint, bytes memory){ RLPReader.RLPItem[] memory values = rawTransaction.toRlpItem().toList(); // must convert to an rlpItem first! return (values[0].toUint(), values[1].toUint(), values[2].toUint(), values[3].toAddress(), values[4].toUint(), values[5].toBytes()); } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { if (item.length == 0) return RLPItem(0, 0); uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory result) { require(isList(item), "isList failed"); uint items = numItems(item); result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } } /* * Helpers */ // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) internal pure returns (uint) { uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) internal pure returns (uint len) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 1; else if (byte0 < STRING_LONG_START) return byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len len := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { return byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length len := add(dataLen, add(byteLen, 1)) } } } // @return number of bytes until the data function _payloadOffset(uint memPtr) internal pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1, "Invalid RLPItem. Booleans are encoded in 1 byte"); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix according to RLP spec require(item.len <= 21, "Invalid RLPItem. Addresses are encoded in 20 bytes or less"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; uint memPtr = item.memPtr + offset; uint result; assembly { result := div(mload(memPtr), exp(256, sub(32, len))) // shift to the correct location } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint offset = _payloadOffset(item.memPtr); uint len = item.len - offset; // data length bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) internal pure { // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } contract VersionRegistry is IVersionRegistry, Ownable { function addVersion(bytes32 id, bytes32 version, string calldata value) external override onlyOwner { require(id != bytes32(0), "missing id"); require(version != bytes32(0), "missing version"); emit VersionAdded(id, version, value, block.timestamp); } function cancelVersion(bytes32 id, bytes32 version, string calldata reason) external override onlyOwner { emit VersionCanceled(id, version, reason); } } abstract contract BasePaymaster is IPaymaster, Ownable { IRelayHub internal relayHub; IForwarder public override trustedForwarder; function getHubAddr() public override view returns (address) { return address(relayHub); } //overhead of forwarder verify+signature, plus hub overhead. uint256 constant public FORWARDER_HUB_OVERHEAD = 50000; //These parameters are documented in IPaymaster.GasLimits uint256 constant public PRE_RELAYED_CALL_GAS_LIMIT = 100000; uint256 constant public POST_RELAYED_CALL_GAS_LIMIT = 110000; uint256 constant public PAYMASTER_ACCEPTANCE_BUDGET = PRE_RELAYED_CALL_GAS_LIMIT + FORWARDER_HUB_OVERHEAD; function getGasLimits() public override virtual view returns ( IPaymaster.GasLimits memory limits ) { return IPaymaster.GasLimits( PAYMASTER_ACCEPTANCE_BUDGET, PRE_RELAYED_CALL_GAS_LIMIT, POST_RELAYED_CALL_GAS_LIMIT ); } // this method must be called from preRelayedCall to validate that the forwarder // is approved by the paymaster as well as by the recipient contract. function _verifyForwarder(GsnTypes.RelayRequest calldata relayRequest) public view { require(address(trustedForwarder) == relayRequest.relayData.forwarder, "Forwarder is not trusted"); GsnEip712Library.verifyForwarderTrusted(relayRequest); } /* * modifier to be used by recipients as access control protection for preRelayedCall & postRelayedCall */ modifier relayHubOnly() { require(msg.sender == getHubAddr(), "Function can only be called by RelayHub"); _; } function setRelayHub(IRelayHub hub) public onlyOwner { relayHub = hub; } function setTrustedForwarder(IForwarder forwarder) public onlyOwner { trustedForwarder = forwarder; } /// check current deposit on relay hub. // (wanted to name it "getRelayHubDeposit()", but we use the name from IRelayRecipient... function getRelayHubDeposit() public override view returns (uint) { return relayHub.balanceOf(address(this)); } // any money moved into the paymaster is transferred as a deposit. // This way, we don't need to understand the RelayHub API in order to replenish // the paymaster. receive() external virtual payable { require(address(relayHub) != address(0), "relay hub address not set"); relayHub.depositFor{value:msg.value}(address(this)); } /// withdraw deposit from relayHub function withdrawRelayHubDepositTo(uint amount, address payable target) public onlyOwner { relayHub.withdraw(amount, target); } } abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize(),20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr,32), size) calldatacopy(add(ptr,64), 0, size) return(ptr, add(size,64)) } } else { return msg.data; } } } contract Penalizer is IPenalizer{ string public override versionPenalizer = "2.0.0+opengsn.penalizer.ipenalizer"; using ECDSA for bytes32; function decodeTransaction(bytes memory rawTransaction) private pure returns (Transaction memory transaction) { (transaction.nonce, transaction.gasPrice, transaction.gasLimit, transaction.to, transaction.value, transaction.data) = RLPReader.decodeTransaction(rawTransaction); return transaction; } modifier relayManagerOnly(IRelayHub hub) { require(hub.isRelayManagerStaked(msg.sender), "Unknown relay manager"); _; } function penalizeRepeatedNonce( bytes memory unsignedTx1, bytes memory signature1, bytes memory unsignedTx2, bytes memory signature2, IRelayHub hub ) public override relayManagerOnly(hub) { // Can be called by a relay manager only. // If a relay attacked the system by signing multiple transactions with the same nonce // (so only one is accepted), anyone can grab both transactions from the blockchain and submit them here. // Check whether unsignedTx1 != unsignedTx2, that both are signed by the same address, // and that unsignedTx1.nonce == unsignedTx2.nonce. // If all conditions are met, relay is considered an "offending relay". // The offending relay will be unregistered immediately, its stake will be forfeited and given // to the address who reported it (msg.sender), thus incentivizing anyone to report offending relays. // If reported via a relay, the forfeited stake is split between // msg.sender (the relay used for reporting) and the address that reported it. address addr1 = keccak256(abi.encodePacked(unsignedTx1)).recover(signature1); address addr2 = keccak256(abi.encodePacked(unsignedTx2)).recover(signature2); require(addr1 == addr2, "Different signer"); require(addr1 != address(0), "ecrecover failed"); Transaction memory decodedTx1 = decodeTransaction(unsignedTx1); Transaction memory decodedTx2 = decodeTransaction(unsignedTx2); // checking that the same nonce is used in both transaction, with both signed by the same address // and the actual data is different // note: we compare the hash of the tx to save gas over iterating both byte arrays require(decodedTx1.nonce == decodedTx2.nonce, "Different nonce"); bytes memory dataToCheck1 = abi.encodePacked(decodedTx1.data, decodedTx1.gasLimit, decodedTx1.to, decodedTx1.value); bytes memory dataToCheck2 = abi.encodePacked(decodedTx2.data, decodedTx2.gasLimit, decodedTx2.to, decodedTx2.value); require(keccak256(dataToCheck1) != keccak256(dataToCheck2), "tx is equal"); penalize(addr1, hub); } function penalizeIllegalTransaction( bytes memory unsignedTx, bytes memory signature, IRelayHub hub ) public override relayManagerOnly(hub) { Transaction memory decodedTx = decodeTransaction(unsignedTx); if (decodedTx.to == address(hub)) { bytes4 selector = GsnUtils.getMethodSig(decodedTx.data); bool isWrongMethodCall = selector != IRelayHub.relayCall.selector; bool isGasLimitWrong = GsnUtils.getParam(decodedTx.data, 4) != decodedTx.gasLimit; require( isWrongMethodCall || isGasLimitWrong, "Legal relay transaction"); } address relay = keccak256(abi.encodePacked(unsignedTx)).recover(signature); require(relay != address(0), "ecrecover failed"); penalize(relay, hub); } function penalize(address relayWorker, IRelayHub hub) private { hub.penalize(relayWorker, msg.sender); } } contract RelayHub is IRelayHub { using SafeMath for uint256; string public override versionHub = "2.0.0+opengsn.hub.irelayhub"; uint256 public override minimumStake; uint256 public override minimumUnstakeDelay; uint256 public override maximumRecipientDeposit; uint256 public override gasOverhead; uint256 public override postOverhead; uint256 public override gasReserve; uint256 public override maxWorkerCount; IStakeManager override public stakeManager; address override public penalizer; // maps relay worker's address to its manager's address mapping(address => address) public override workerToManager; // maps relay managers to the number of their workers mapping(address => uint256) public override workerCount; mapping(address => uint256) private balances; constructor ( IStakeManager _stakeManager, address _penalizer, uint256 _maxWorkerCount, uint256 _gasReserve, uint256 _postOverhead, uint256 _gasOverhead, uint256 _maximumRecipientDeposit, uint256 _minimumUnstakeDelay, uint256 _minimumStake ) public { stakeManager = _stakeManager; penalizer = _penalizer; maxWorkerCount = _maxWorkerCount; gasReserve = _gasReserve; postOverhead = _postOverhead; gasOverhead = _gasOverhead; maximumRecipientDeposit = _maximumRecipientDeposit; minimumUnstakeDelay = _minimumUnstakeDelay; minimumStake = _minimumStake; } function registerRelayServer(uint256 baseRelayFee, uint256 pctRelayFee, string calldata url) external override { address relayManager = msg.sender; require( isRelayManagerStaked(relayManager), "relay manager not staked" ); require(workerCount[relayManager] > 0, "no relay workers"); emit RelayServerRegistered(relayManager, baseRelayFee, pctRelayFee, url); } function addRelayWorkers(address[] calldata newRelayWorkers) external override { address relayManager = msg.sender; workerCount[relayManager] = workerCount[relayManager] + newRelayWorkers.length; require(workerCount[relayManager] <= maxWorkerCount, "too many workers"); require( isRelayManagerStaked(relayManager), "relay manager not staked" ); for (uint256 i = 0; i < newRelayWorkers.length; i++) { require(workerToManager[newRelayWorkers[i]] == address(0), "this worker has a manager"); workerToManager[newRelayWorkers[i]] = relayManager; } emit RelayWorkersAdded(relayManager, newRelayWorkers, workerCount[relayManager]); } function depositFor(address target) public override payable { uint256 amount = msg.value; require(amount <= maximumRecipientDeposit, "deposit too big"); balances[target] = balances[target].add(amount); emit Deposited(target, msg.sender, amount); } function balanceOf(address target) external override view returns (uint256) { return balances[target]; } function withdraw(uint256 amount, address payable dest) public override { address payable account = msg.sender; require(balances[account] >= amount, "insufficient funds"); balances[account] = balances[account].sub(amount); dest.transfer(amount); emit Withdrawn(account, dest, amount); } function verifyGasLimits( uint256 paymasterMaxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, uint256 initialGas ) private view returns (IPaymaster.GasLimits memory gasLimits, uint256 maxPossibleGas) { gasLimits = IPaymaster(relayRequest.relayData.paymaster).getGasLimits{gas:50000}(); require(paymasterMaxAcceptanceBudget >= gasLimits.acceptanceBudget, "unexpected high acceptanceBudget"); maxPossibleGas = gasOverhead.add( gasLimits.preRelayedCallGasLimit).add( gasLimits.postRelayedCallGasLimit).add( relayRequest.request.gas); // This transaction must have enough gas to forward the call to the recipient with the requested amount, and not // run out of gas later in this function. require( initialGas >= maxPossibleGas, "Not enough gas left for innerRelayCall to complete"); uint256 maxPossibleCharge = calculateCharge( maxPossibleGas, relayRequest.relayData ); // We don't yet know how much gas will be used by the recipient, so we make sure there are enough funds to pay // for the maximum possible charge. require(maxPossibleCharge <= balances[relayRequest.relayData.paymaster], "Paymaster balance too low"); } struct RelayCallData { bool success; bytes4 functionSelector; bytes recipientContext; bytes relayedCallReturnValue; IPaymaster.GasLimits gasLimits; RelayCallStatus status; uint256 innerGasUsed; uint256 maxPossibleGas; uint256 gasBeforeInner; bytes retData; } function relayCall( uint paymasterMaxAcceptanceBudget, GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint externalGasLimit ) external override returns (bool paymasterAccepted, bytes memory returnValue) { (signature); RelayCallData memory vars; vars.functionSelector = MinLibBytes.readBytes4(relayRequest.request.data, 0); require(msg.sender == tx.origin, "relay worker cannot be a smart contract"); require(workerToManager[msg.sender] != address(0), "Unknown relay worker"); require(relayRequest.relayData.relayWorker == msg.sender, "Not a right worker"); require( isRelayManagerStaked(workerToManager[msg.sender]), "relay manager not staked" ); require(relayRequest.relayData.gasPrice <= tx.gasprice, "Invalid gas price"); require(externalGasLimit <= block.gaslimit, "Impossible gas limit"); (vars.gasLimits, vars.maxPossibleGas) = verifyGasLimits(paymasterMaxAcceptanceBudget, relayRequest, externalGasLimit); { //How much gas to pass down to innerRelayCall. must be lower than the default 63/64 // actually, min(gasleft*63/64, gasleft-GAS_RESERVE) might be enough. uint256 innerGasLimit = gasleft()*63/64-gasReserve; vars.gasBeforeInner = gasleft(); uint256 _tmpInitialGas = innerGasLimit + externalGasLimit + gasOverhead + postOverhead; // Calls to the recipient are performed atomically inside an inner transaction which may revert in case of // errors in the recipient. In either case (revert or regular execution) the return data encodes the // RelayCallStatus value. (bool success, bytes memory relayCallStatus) = address(this).call{gas:innerGasLimit}( abi.encodeWithSelector(RelayHub.innerRelayCall.selector, relayRequest, signature, approvalData, vars.gasLimits, _tmpInitialGas - gasleft(), vars.maxPossibleGas ) ); vars.success = success; vars.innerGasUsed = vars.gasBeforeInner-gasleft(); (vars.status, vars.relayedCallReturnValue) = abi.decode(relayCallStatus, (RelayCallStatus, bytes)); if ( vars.relayedCallReturnValue.length>0 ) { emit TransactionResult(vars.status, vars.relayedCallReturnValue); } } { if (!vars.success) { //Failure cases where the PM doesn't pay if ( (vars.innerGasUsed < vars.gasLimits.acceptanceBudget ) && ( vars.status == RelayCallStatus.RejectedByPreRelayed || vars.status == RelayCallStatus.RejectedByForwarder || vars.status == RelayCallStatus.RejectedByRecipientRevert //can only be thrown if rejectOnRecipientRevert==true )) { paymasterAccepted=false; emit TransactionRejectedByPaymaster( workerToManager[msg.sender], relayRequest.relayData.paymaster, relayRequest.request.from, relayRequest.request.to, msg.sender, vars.functionSelector, vars.innerGasUsed, vars.relayedCallReturnValue); return (false, vars.relayedCallReturnValue); } } // We now perform the actual charge calculation, based on the measured gas used uint256 gasUsed = (externalGasLimit - gasleft()) + gasOverhead; uint256 charge = calculateCharge(gasUsed, relayRequest.relayData); balances[relayRequest.relayData.paymaster] = balances[relayRequest.relayData.paymaster].sub(charge); balances[workerToManager[msg.sender]] = balances[workerToManager[msg.sender]].add(charge); emit TransactionRelayed( workerToManager[msg.sender], msg.sender, relayRequest.request.from, relayRequest.request.to, relayRequest.relayData.paymaster, vars.functionSelector, vars.status, charge); return (true, ""); } } struct InnerRelayCallData { uint256 balanceBefore; bytes32 preReturnValue; bool relayedCallSuccess; bytes relayedCallReturnValue; bytes recipientContext; bytes data; bool rejectOnRecipientRevert; } function innerRelayCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, IPaymaster.GasLimits calldata gasLimits, uint256 totalInitialGas, uint256 maxPossibleGas ) external returns (RelayCallStatus, bytes memory) { InnerRelayCallData memory vars; // A new gas measurement is performed inside innerRelayCall, since // due to EIP150 available gas amounts cannot be directly compared across external calls // This external function can only be called by RelayHub itself, creating an internal transaction. Calls to the // recipient (preRelayedCall, the relayedCall, and postRelayedCall) are called from inside this transaction. require(msg.sender == address(this), "Only RelayHub should call this function"); // If either pre or post reverts, the whole internal transaction will be reverted, reverting all side effects on // the recipient. The recipient will still be charged for the used gas by the relay. // The recipient is no allowed to withdraw balance from RelayHub during a relayed transaction. We check pre and // post state to ensure this doesn't happen. vars.balanceBefore = balances[relayRequest.relayData.paymaster]; // First preRelayedCall is executed. // Note: we open a new block to avoid growing the stack too much. vars.data = abi.encodeWithSelector( IPaymaster.preRelayedCall.selector, relayRequest, signature, approvalData, maxPossibleGas ); { bool success; bytes memory retData; (success, retData) = relayRequest.relayData.paymaster.call{gas:gasLimits.preRelayedCallGasLimit}(vars.data); if (!success) { GsnEip712Library.truncateInPlace(retData); revertWithStatus(RelayCallStatus.RejectedByPreRelayed, retData); } (vars.recipientContext, vars.rejectOnRecipientRevert) = abi.decode(retData, (bytes,bool)); } // The actual relayed call is now executed. The sender's address is appended at the end of the transaction data { bool forwarderSuccess; (forwarderSuccess, vars.relayedCallSuccess, vars.relayedCallReturnValue) = GsnEip712Library.execute(relayRequest, signature); if ( !forwarderSuccess ) { revertWithStatus(RelayCallStatus.RejectedByForwarder, vars.relayedCallReturnValue); } if (vars.rejectOnRecipientRevert && !vars.relayedCallSuccess) { //we trusted the recipient, but it reverted... revertWithStatus(RelayCallStatus.RejectedByRecipientRevert, vars.relayedCallReturnValue); } } // Finally, postRelayedCall is executed, with the relayedCall execution's status and a charge estimate // We now determine how much the recipient will be charged, to pass this value to postRelayedCall for accurate // accounting. vars.data = abi.encodeWithSelector( IPaymaster.postRelayedCall.selector, vars.recipientContext, vars.relayedCallSuccess, totalInitialGas - gasleft(), /*gasUseWithoutPost*/ relayRequest.relayData ); { (bool successPost,bytes memory ret) = relayRequest.relayData.paymaster.call{gas:gasLimits.postRelayedCallGasLimit}(vars.data); if (!successPost) { revertWithStatus(RelayCallStatus.PostRelayedFailed, ret); } } if (balances[relayRequest.relayData.paymaster] < vars.balanceBefore) { revertWithStatus(RelayCallStatus.PaymasterBalanceChanged, ""); } return (vars.relayedCallSuccess ? RelayCallStatus.OK : RelayCallStatus.RelayedCallFailed, vars.relayedCallReturnValue); } /** * @dev Reverts the transaction with return data set to the ABI encoding of the status argument (and revert reason data) */ function revertWithStatus(RelayCallStatus status, bytes memory ret) private pure { bytes memory data = abi.encode(status, ret); GsnEip712Library.truncateInPlace(data); assembly { let dataSize := mload(data) let dataPtr := add(data, 32) revert(dataPtr, dataSize) } } function calculateCharge(uint256 gasUsed, GsnTypes.RelayData calldata relayData) public override virtual view returns (uint256) { // relayData.baseRelayFee + (gasUsed * relayData.gasPrice * (100 + relayData.pctRelayFee)) / 100; return relayData.baseRelayFee.add((gasUsed.mul(relayData.gasPrice).mul(relayData.pctRelayFee.add(100))).div(100)); } function isRelayManagerStaked(address relayManager) public override view returns (bool) { return stakeManager.isRelayManagerStaked(relayManager, address(this), minimumStake, minimumUnstakeDelay); } modifier penalizerOnly () { require(msg.sender == penalizer, "Not penalizer"); _; } function penalize(address relayWorker, address payable beneficiary) external override penalizerOnly { address relayManager = workerToManager[relayWorker]; // The worker must be controlled by a manager with a locked stake require(relayManager != address(0), "Unknown relay worker"); require( isRelayManagerStaked(relayManager), "relay manager not staked" ); IStakeManager.StakeInfo memory stakeInfo = stakeManager.getStakeInfo(relayManager); stakeManager.penalizeRelayManager(relayManager, beneficiary, stakeInfo.stake); } } contract StakeManager is IStakeManager { using SafeMath for uint256; string public override versionSM = "2.0.0+opengsn.stakemanager.istakemanager"; /// maps relay managers to their stakes mapping(address => StakeInfo) public stakes; function getStakeInfo(address relayManager) external override view returns (StakeInfo memory stakeInfo) { return stakes[relayManager]; } /// maps relay managers to a map of addressed of their authorized hubs to the information on that hub mapping(address => mapping(address => RelayHubInfo)) public authorizedHubs; /// Put a stake for a relayManager and set its unstake delay. /// If the entry does not exist, it is created, and the caller of this function becomes its owner. /// If the entry already exists, only the owner can call this function. /// @param relayManager - address that represents a stake entry and controls relay registrations on relay hubs /// @param unstakeDelay - number of blocks to elapse before the owner can retrieve the stake after calling 'unlock' function stakeForAddress(address relayManager, uint256 unstakeDelay) external override payable { require(stakes[relayManager].owner == address(0) || stakes[relayManager].owner == msg.sender, "not owner"); require(unstakeDelay >= stakes[relayManager].unstakeDelay, "unstakeDelay cannot be decreased"); require(msg.sender != relayManager, "relayManager cannot stake for itself"); require(stakes[msg.sender].owner == address(0), "sender is a relayManager itself"); stakes[relayManager].owner = msg.sender; stakes[relayManager].stake += msg.value; stakes[relayManager].unstakeDelay = unstakeDelay; emit StakeAdded(relayManager, stakes[relayManager].owner, stakes[relayManager].stake, stakes[relayManager].unstakeDelay); } function unlockStake(address relayManager) external override { StakeInfo storage info = stakes[relayManager]; require(info.owner == msg.sender, "not owner"); require(info.withdrawBlock == 0, "already pending"); info.withdrawBlock = block.number.add(info.unstakeDelay); emit StakeUnlocked(relayManager, msg.sender, info.withdrawBlock); } function withdrawStake(address relayManager) external override { StakeInfo storage info = stakes[relayManager]; require(info.owner == msg.sender, "not owner"); require(info.withdrawBlock > 0, "Withdrawal is not scheduled"); require(info.withdrawBlock <= block.number, "Withdrawal is not due"); uint256 amount = info.stake; delete stakes[relayManager]; msg.sender.transfer(amount); emit StakeWithdrawn(relayManager, msg.sender, amount); } modifier ownerOnly (address relayManager) { StakeInfo storage info = stakes[relayManager]; require(info.owner == msg.sender, "not owner"); _; } modifier managerOnly () { StakeInfo storage info = stakes[msg.sender]; require(info.owner != address(0), "not manager"); _; } function authorizeHubByOwner(address relayManager, address relayHub) external ownerOnly(relayManager) override { _authorizeHub(relayManager, relayHub); } function authorizeHubByManager(address relayHub) external managerOnly override { _authorizeHub(msg.sender, relayHub); } function _authorizeHub(address relayManager, address relayHub) internal { authorizedHubs[relayManager][relayHub].removalBlock = uint(-1); emit HubAuthorized(relayManager, relayHub); } function unauthorizeHubByOwner(address relayManager, address relayHub) external override ownerOnly(relayManager) { _unauthorizeHub(relayManager, relayHub); } function unauthorizeHubByManager(address relayHub) external override managerOnly { _unauthorizeHub(msg.sender, relayHub); } function _unauthorizeHub(address relayManager, address relayHub) internal { RelayHubInfo storage hubInfo = authorizedHubs[relayManager][relayHub]; require(hubInfo.removalBlock == uint(-1), "hub not authorized"); uint256 removalBlock = block.number.add(stakes[relayManager].unstakeDelay); hubInfo.removalBlock = removalBlock; emit HubUnauthorized(relayManager, relayHub, removalBlock); } function isRelayManagerStaked(address relayManager, address relayHub, uint256 minAmount, uint256 minUnstakeDelay) external override view returns (bool) { StakeInfo storage info = stakes[relayManager]; bool isAmountSufficient = info.stake >= minAmount; bool isDelaySufficient = info.unstakeDelay >= minUnstakeDelay; bool isStakeLocked = info.withdrawBlock == 0; bool isHubAuthorized = authorizedHubs[relayManager][relayHub].removalBlock == uint(-1); return isAmountSufficient && isDelaySufficient && isStakeLocked && isHubAuthorized; } /// Slash the stake of the relay relayManager. In order to prevent stake kidnapping, burns half of stake on the way. /// @param relayManager - entry to penalize /// @param beneficiary - address that receives half of the penalty amount /// @param amount - amount to withdraw from stake function penalizeRelayManager(address relayManager, address payable beneficiary, uint256 amount) external override { uint256 removalBlock = authorizedHubs[relayManager][msg.sender].removalBlock; require(removalBlock != 0, "hub not authorized"); require(removalBlock > block.number, "hub authorization expired"); // Half of the stake will be burned (sent to address 0) require(stakes[relayManager].stake >= amount, "penalty exceeds stake"); stakes[relayManager].stake = SafeMath.sub(stakes[relayManager].stake, amount); uint256 toBurn = SafeMath.div(amount, 2); uint256 reward = SafeMath.sub(amount, toBurn); // Ether is burned and transferred address(0).transfer(toBurn); beneficiary.transfer(reward); emit StakePenalized(relayManager, beneficiary, reward); } } contract Forwarder is IForwarder { using ECDSA for bytes32; string public constant GENERIC_PARAMS = "address from,address to,uint256 value,uint256 gas,uint256 nonce,bytes data"; string public constant EIP712_DOMAIN_TYPE = "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"; mapping(bytes32 => bool) public typeHashes; mapping(bytes32 => bool) public domains; // Nonces of senders, used to prevent replay attacks mapping(address => uint256) private nonces; // solhint-disable-next-line no-empty-blocks receive() external payable {} function getNonce(address from) public view override returns (uint256) { return nonces[from]; } constructor() public { string memory requestType = string(abi.encodePacked("ForwardRequest(", GENERIC_PARAMS, ")")); registerRequestTypeInternal(requestType); } function verify( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig) external override view { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); } function execute( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes calldata suffixData, bytes calldata sig ) external payable override returns (bool success, bytes memory ret) { _verifyNonce(req); _verifySig(req, domainSeparator, requestTypeHash, suffixData, sig); _updateNonce(req); // solhint-disable-next-line avoid-low-level-calls (success,ret) = req.to.call{gas : req.gas, value : req.value}(abi.encodePacked(req.data, req.from)); if ( address(this).balance>0 ) { //can't fail: req.from signed (off-chain) the request, so it must be an EOA... payable(req.from).transfer(address(this).balance); } return (success,ret); } function _verifyNonce(ForwardRequest memory req) internal view { require(nonces[req.from] == req.nonce, "nonce mismatch"); } function _updateNonce(ForwardRequest memory req) internal { nonces[req.from]++; } function registerRequestType(string calldata typeName, string calldata typeSuffix) external override { for (uint i = 0; i < bytes(typeName).length; i++) { bytes1 c = bytes(typeName)[i]; require(c != "(" && c != ")", "invalid typename"); } string memory requestType = string(abi.encodePacked(typeName, "(", GENERIC_PARAMS, ",", typeSuffix)); registerRequestTypeInternal(requestType); } function registerDomainSeparator(string calldata name, string calldata version) external override { uint256 chainId; /* solhint-disable-next-line no-inline-assembly */ assembly { chainId := chainid() } bytes memory domainValue = abi.encode( keccak256(bytes(EIP712_DOMAIN_TYPE)), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this)); bytes32 domainHash = keccak256(domainValue); domains[domainHash] = true; emit DomainRegistered(domainHash, domainValue); } function registerRequestTypeInternal(string memory requestType) internal { bytes32 requestTypehash = keccak256(bytes(requestType)); typeHashes[requestTypehash] = true; emit RequestTypeRegistered(requestTypehash, requestType); } event DomainRegistered(bytes32 indexed domainSeparator, bytes domainValue); event RequestTypeRegistered(bytes32 indexed typeHash, string typeStr); function _verifySig( ForwardRequest memory req, bytes32 domainSeparator, bytes32 requestTypeHash, bytes memory suffixData, bytes memory sig) internal view { require(domains[domainSeparator], "unregistered domain separator"); require(typeHashes[requestTypeHash], "unregistered request typehash"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", domainSeparator, keccak256(_getEncoded(req, requestTypeHash, suffixData)) )); require(digest.recover(sig) == req.from, "signature mismatch"); } function _getEncoded( ForwardRequest memory req, bytes32 requestTypeHash, bytes memory suffixData ) public pure returns ( bytes memory ) { return abi.encodePacked( requestTypeHash, abi.encode( req.from, req.to, req.value, req.gas, req.nonce, keccak256(req.data) ), suffixData ); } } contract TestForwarderTarget is BaseRelayRecipient { string public override versionRecipient = "2.0.0+opengsn.test.recipient"; constructor(address forwarder) public { trustedForwarder = forwarder; } // solhint-disable-next-line no-empty-blocks receive() external payable {} event TestForwarderMessage(string message, address realSender, address msgSender, address origin); function emitMessage(string memory message) public { // solhint-disable-next-line avoid-tx-origin emit TestForwarderMessage(message, _msgSender(), msg.sender, tx.origin); } function publicMsgSender() public view returns (address) { return _msgSender(); } function publicMsgData() public view returns (bytes memory) { return _msgData(); } function mustReceiveEth(uint value) public payable { require( msg.value == value, "didn't receive value"); } event Reverting(string message); function testRevert() public { require(address(this) == address(0), "always fail"); emit Reverting("if you see this revert failed..."); } } contract PayableWithEmit is BaseRelayRecipient { string public override versionRecipient = "2.0.0+opengsn.payablewithemit.irelayrecipient"; event Received(address sender, uint value, uint gasleft); receive () external payable { emit Received(_msgSender(), msg.value, gasleft()); } //helper: send value to another contract function doSend(address payable target) public payable { uint before = gasleft(); // solhint-disable-next-line check-send-result bool success = target.send(msg.value); uint gasAfter = gasleft(); emit GasUsed(before-gasAfter, success); } event GasUsed(uint gasUsed, bool success); } contract TestPaymasterEverythingAccepted is BasePaymaster { function versionPaymaster() external view override virtual returns (string memory){ return "2.0.0+opengsn.test-pea.ipaymaster"; } event SampleRecipientPreCall(); event SampleRecipientPostCall(bool success, uint actualCharge); function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override virtual returns (bytes memory, bool) { (signature); _verifyForwarder(relayRequest); (approvalData, maxPossibleGas); emit SampleRecipientPreCall(); return ("no revert here",false); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override virtual { (context, gasUseWithoutPost, relayData); emit SampleRecipientPostCall(success, gasUseWithoutPost); } function deposit() public payable { require(address(relayHub) != address(0), "relay hub address not set"); relayHub.depositFor{value:msg.value}(address(this)); } function withdrawAll(address payable destination) public { uint256 amount = relayHub.balanceOf(address(this)); withdrawRelayHubDepositTo(amount, destination); } } contract TestPaymasterOwnerSignature is TestPaymasterEverythingAccepted { using ECDSA for bytes32; /** * This demonstrates how dapps can provide an off-chain signatures to relayed transactions. */ function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override returns (bytes memory, bool) { (signature, maxPossibleGas); _verifyForwarder(relayRequest); address signer = keccak256(abi.encodePacked("I approve", relayRequest.request.from)) .toEthSignedMessageHash() .recover(approvalData); require(signer == owner(), "test: not approved"); return ("",false); } } contract TestPaymasterPreconfiguredApproval is TestPaymasterEverythingAccepted { bytes public expectedApprovalData; function setExpectedApprovalData(bytes memory val) public { expectedApprovalData = val; } function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override returns (bytes memory, bool) { (relayRequest, signature, approvalData, maxPossibleGas); _verifyForwarder(relayRequest); require(keccak256(expectedApprovalData) == keccak256(approvalData), string(abi.encodePacked( "test: unexpected approvalData: '", approvalData, "' instead of '", expectedApprovalData, "'"))); return ("",false); } } contract TestPaymasterStoreContext is TestPaymasterEverythingAccepted { event SampleRecipientPreCallWithValues( address relay, address from, bytes encodedFunction, uint256 baseRelayFee, uint256 pctRelayFee, uint256 gasPrice, uint256 gasLimit, bytes approvalData, uint256 maxPossibleGas ); event SampleRecipientPostCallWithValues( string context ); /** * This demonstrates how preRelayedCall can return 'context' data for reuse in postRelayedCall. */ function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override returns (bytes memory, bool) { (signature, approvalData, maxPossibleGas); _verifyForwarder(relayRequest); emit SampleRecipientPreCallWithValues( relayRequest.relayData.relayWorker, relayRequest.request.from, relayRequest.request.data, relayRequest.relayData.baseRelayFee, relayRequest.relayData.pctRelayFee, relayRequest.relayData.gasPrice, relayRequest.request.gas, approvalData, maxPossibleGas); return ("context passed from preRelayedCall to postRelayedCall",false); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override relayHubOnly { (context, success, gasUseWithoutPost, relayData); emit SampleRecipientPostCallWithValues(string(context)); } } contract TestPaymasterVariableGasLimits is TestPaymasterEverythingAccepted { string public override versionPaymaster = "2.0.0+opengsn.test-vgl.ipaymaster"; event SampleRecipientPreCallWithValues( uint256 gasleft, uint256 maxPossibleGas ); event SampleRecipientPostCallWithValues( uint256 gasleft, uint256 gasUseWithoutPost ); function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override returns (bytes memory, bool) { (signature, approvalData); _verifyForwarder(relayRequest); emit SampleRecipientPreCallWithValues( gasleft(), maxPossibleGas); return ("", false); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override relayHubOnly { (context, success, gasUseWithoutPost, relayData); emit SampleRecipientPostCallWithValues(gasleft(), gasUseWithoutPost); } } contract TestRecipient is BaseRelayRecipient, IKnowForwarderAddress { string public override versionRecipient = "2.0.0+opengsn.test.irelayrecipient"; constructor(address forwarder) public { setTrustedForwarder(forwarder); } function getTrustedForwarder() public override view returns(address) { return trustedForwarder; } function setTrustedForwarder(address forwarder) internal { trustedForwarder = forwarder; } event Reverting(string message); function testRevert() public { require(address(this) == address(0), "always fail"); emit Reverting("if you see this revert failed..."); } address payable public paymaster; function setWithdrawDuringRelayedCall(address payable _paymaster) public { paymaster = _paymaster; } // solhint-disable-next-line no-empty-blocks receive() external payable {} event SampleRecipientEmitted(string message, address realSender, address msgSender, address origin, uint256 msgValue, uint256 balance); function emitMessage(string memory message) public payable returns (string memory) { if (paymaster != address(0)) { withdrawAllBalance(); } emit SampleRecipientEmitted(message, _msgSender(), msg.sender, tx.origin, msg.value, address(this).balance); return "emitMessage return value"; } function withdrawAllBalance() public { TestPaymasterConfigurableMisbehavior(paymaster).withdrawAllBalance(); } // solhint-disable-next-line no-empty-blocks function dontEmitMessage(string memory message) public {} function emitMessageNoParams() public { emit SampleRecipientEmitted("Method with no parameters", _msgSender(), msg.sender, tx.origin, 0, address(this).balance); } //return (or revert) with a string in the given length function checkReturnValues(uint len, bool doRevert) public view returns (string memory) { (this); string memory mesg = "this is a long message that we are going to return a small part from. we don't use a loop since we want a fixed gas usage of the method itself."; require( bytes(mesg).length>=len, "invalid len: too large"); /* solhint-disable no-inline-assembly */ //cut the msg at that length assembly { mstore(mesg, len) } require(!doRevert, mesg); return mesg; } //function with no return value (also test revert with no msg. function checkNoReturnValues(bool doRevert) public view { (this); require(!doRevert); } } contract BatchForwarder is Forwarder, BaseRelayRecipient { string public override versionRecipient = "2.0.0+opengsn.batched.irelayrecipient"; constructor() public { //needed for sendBatch trustedForwarder = address(this); } function sendBatch(address[] calldata targets, bytes[] calldata encodedFunctions) external { require(targets.length == encodedFunctions.length); address sender = _msgSender(); for (uint i = 0; i < targets.length; i++) { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory ret) = targets[i].call(abi.encodePacked(encodedFunctions[i], sender)); // TODO: currently, relayed transaction does not report exception string. when it does, this // will propagate the inner call exception description if (!success){ //re-throw the revert with the same revert reason. GsnUtils.revertWithData(ret); } } } } contract TestPaymasterConfigurableMisbehavior is TestPaymasterEverythingAccepted { bool public withdrawDuringPostRelayedCall; bool public withdrawDuringPreRelayedCall; bool public returnInvalidErrorCode; bool public revertPostRelayCall; bool public overspendAcceptGas; bool public revertPreRelayCall; bool public greedyAcceptanceBudget; bool public expensiveGasLimits; function setWithdrawDuringPostRelayedCall(bool val) public { withdrawDuringPostRelayedCall = val; } function setWithdrawDuringPreRelayedCall(bool val) public { withdrawDuringPreRelayedCall = val; } function setReturnInvalidErrorCode(bool val) public { returnInvalidErrorCode = val; } function setRevertPostRelayCall(bool val) public { revertPostRelayCall = val; } function setRevertPreRelayCall(bool val) public { revertPreRelayCall = val; } function setOverspendAcceptGas(bool val) public { overspendAcceptGas = val; } function setGreedyAcceptanceBudget(bool val) public { greedyAcceptanceBudget = val; } function setExpensiveGasLimits(bool val) public { expensiveGasLimits = val; } function preRelayedCall( GsnTypes.RelayRequest calldata relayRequest, bytes calldata signature, bytes calldata approvalData, uint256 maxPossibleGas ) external override relayHubOnly returns (bytes memory, bool) { (signature, approvalData, maxPossibleGas); _verifyForwarder(relayRequest); if (overspendAcceptGas) { uint i = 0; while (true) { i++; } } require(!returnInvalidErrorCode, "invalid code"); if (withdrawDuringPreRelayedCall) { withdrawAllBalance(); } if (revertPreRelayCall) { revert("You asked me to revert, remember?"); } return ("", trustRecipientRevert); } function postRelayedCall( bytes calldata context, bool success, uint256 gasUseWithoutPost, GsnTypes.RelayData calldata relayData ) external override relayHubOnly { (context, success, gasUseWithoutPost, relayData); if (withdrawDuringPostRelayedCall) { withdrawAllBalance(); } if (revertPostRelayCall) { revert("You asked me to revert, remember?"); } } /// leaving withdrawal public and unprotected function withdrawAllBalance() public returns (uint256) { require(address(relayHub) != address(0), "relay hub address not set"); uint256 balance = relayHub.balanceOf(address(this)); relayHub.withdraw(balance, address(this)); return balance; } IPaymaster.GasLimits private limits = super.getGasLimits(); function getGasLimits() public override view returns (IPaymaster.GasLimits memory) { if (expensiveGasLimits) { uint sum; //memory access is 700gas, so we waste ~50000 for ( int i=0; i<60000; i+=700 ) { sum = sum + limits.acceptanceBudget; } } if (greedyAcceptanceBudget) { return IPaymaster.GasLimits(limits.acceptanceBudget * 9, limits.preRelayedCallGasLimit, limits.postRelayedCallGasLimit); } return limits; } bool private trustRecipientRevert; function setGasLimits(uint acceptanceBudget, uint preRelayedCallGasLimit, uint postRelayedCallGasLimit) public { limits = IPaymaster.GasLimits( acceptanceBudget, preRelayedCallGasLimit, postRelayedCallGasLimit ); } function setTrustRecipientRevert(bool on) public { trustRecipientRevert = on; } // solhint-disable-next-line no-empty-blocks receive() external override payable {} }
0x6080604052600436106101345760003560e01c8063aa67c919116100ab578063d904c7321161006f578063d904c7321461032a578063e5fad9781461034c578063ebcd31ac14610361578063ec5ffac214610381578063eea7570e14610396578063fbb44607146103ab57610134565b8063aa67c919146102ad578063ba3ecc5b146102c0578063c2da0786146102d5578063c4775a68146102f5578063ca998f561461030a57610134565b806370a08231116100fd57806370a082311461020157806371116320146102215780637542ff951461023657806383b718711461025857806383fea4ef1461027857806386a16f8f1461028d57610134565b8062f714ce14610139578063194ac3071461015b57806327b4256a146101915780632ad311b5146101bf5780633a3e83ac146101ec575b600080fd5b34801561014557600080fd5b5061015961015436600461220b565b6103d9565b005b34801561016757600080fd5b5061017b610176366004611f33565b6104d5565b60405161018891906127e3565b60405180910390f35b34801561019d57600080fd5b506101b16101ac36600461227d565b6104e7565b6040516101889291906127c0565b3480156101cb57600080fd5b506101df6101da366004611f33565b610b3f565b60405161018891906127b5565b3480156101f857600080fd5b5061017b610bd2565b34801561020d57600080fd5b5061017b61021c366004611f33565b610bd8565b34801561022d57600080fd5b5061017b610bf3565b34801561024257600080fd5b5061024b610bf9565b604051610188919061266a565b34801561026457600080fd5b50610159610273366004612320565b610c08565b34801561028457600080fd5b5061017b610cb1565b34801561029957600080fd5b5061017b6102a836600461222f565b610cb7565b6101596102bb366004611f33565b610d1b565b3480156102cc57600080fd5b5061017b610dc4565b3480156102e157600080fd5b506101596102f0366004611f87565b610dca565b34801561030157600080fd5b5061024b610f4b565b34801561031657600080fd5b5061024b610325366004611f33565b610f5a565b34801561033657600080fd5b5061033f610f75565b60405161018891906128b6565b34801561035857600080fd5b5061017b611003565b34801561036d57600080fd5b5061015961037c366004611f4f565b611009565b34801561038d57600080fd5b5061017b611187565b3480156103a257600080fd5b5061017b61118d565b3480156103b757600080fd5b506103cb6103c6366004612100565b611193565b604051610188929190612895565b336000818152600c60205260409020548311156104115760405162461bcd60e51b815260040161040890612bc1565b60405180910390fd5b6001600160a01b0381166000908152600c602052604090205461043a908463ffffffff61151316565b6001600160a01b038083166000908152600c60205260408082209390935591519084169185156108fc02918691818181858888f19350505050158015610484573d6000803e3d6000fd5b50816001600160a01b0316816001600160a01b03167fd1c19fbcd4551a5edfb66d43d2e337c04837afda3482b42bdf569a8fccdae5fb856040516104c891906127e3565b60405180910390a3505050565b600b6020526000908152604090205481565b600060606104f3611d28565b6105486105008a80612e7f565b61050e9060a0810190612e38565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201829052509250611555915050565b6001600160e01b03191660208201523332146105765760405162461bcd60e51b815260040161040890612abe565b336000908152600a60205260409020546001600160a01b03166105ab5760405162461bcd60e51b815260040161040890612c87565b336105b960208b018b612e94565b6105ca906080810190606001611f33565b6001600160a01b0316146105f05760405162461bcd60e51b815260040161040890612bed565b336000908152600a6020526040902054610612906001600160a01b0316610b3f565b61062e5760405162461bcd60e51b815260040161040890612a87565b3a61063c60208b018b612e94565b35111561065b5760405162461bcd60e51b8152600401610408906129ac565b4584111561067b5760405162461bcd60e51b8152600401610408906128c9565b6106868a8a8661158e565b60e0830152608082015260065460009060405a603f02816106a357fe5b040390505a8261010001818152505060006005546004548784010101905060006060306001600160a01b03168463fbb4460760e01b8f8f8f8f8f8c608001515a8c038e60e00151604051602401610701989796959493929190612d58565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b031990941693909317909252905161073f9190612545565b60006040518083038160008787f1925050503d806000811461077d576040519150601f19603f3d011682016040523d82523d6000602084013e610782565b606091505b50811515875290925090505a6101008601510360c086015280516107af90820160209081019083016120a3565b8660a001876060018290528260068111156107c657fe5b60068111156107d157fe5b9052505060608501515115610822577fa1478a4242848419db824250a0dddc645dca0d6a9b12ab1fd79b00145a0ba98e8560a001518660600151604051610819929190612895565b60405180910390a15b5050505080600001516109625760808101515160c0820151108015610889575060028160a00151600681111561085457fe5b148061086f575060038160a00151600681111561086d57fe5b145b80610889575060048160a00151600681111561088757fe5b145b15610962576000925061089c8980612e7f565b6108aa906020810190611f33565b6001600160a01b03166108c060208b018b612e94565b6108d19060a0810190608001611f33565b336000908152600a60205260409020546001600160a01b0391821691167fddb88484d11f800b80fe63aa67488ec56ee001d85896d528912c5d850cbcd06a6109198d80612e7f565b61092a906040810190602001611f33565b3386602001518760c00151886060015160405161094b95949392919061267e565b60405180910390a460600151600092509050610b33565b60006004545a86030190506000610980826102a860208e018e612e94565b90506109d181600c60008e806020019061099a9190612e94565b6109ab9060a0810190608001611f33565b6001600160a01b031681526020810191909152604001600020549063ffffffff61151316565b600c60006109e260208f018f612e94565b6109f39060a0810190608001611f33565b6001600160a01b0390811682526020808301939093526040918201600090812094909455338452600a835281842054168352600c909152902054610a3d908263ffffffff61172e16565b336000908152600a60209081526040808320546001600160a01b03168352600c909152902055610a6d8b80612e7f565b610a7b906020810190611f33565b336000818152600a60205260409020546001600160a01b0392831692167fc9aa709786a3d5fe2cc947abc1ba8cbb0f6decb57aa74b84eb7f558125fee454610ac38f80612e7f565b610ad4906040810190602001611f33565b8f8060200190610ae49190612e94565b610af59060a0810190608001611f33565b88602001518960a0015188604051610b119594939291906126f0565b60405180910390a4600160405180602001604052806000815250945094505050505b97509795505050505050565b600854600154600254604051636de8dd4160e01b81526000936001600160a01b031692636de8dd4192610b7a92879230929091600401612736565b60206040518083038186803b158015610b9257600080fd5b505afa158015610ba6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bca9190611ff3565b90505b919050565b60035481565b6001600160a01b03166000908152600c602052604090205490565b60025481565b6008546001600160a01b031681565b33610c1281610b3f565b610c2e5760405162461bcd60e51b815260040161040890612a87565b6001600160a01b0381166000908152600b6020526040902054610c635760405162461bcd60e51b815260040161040890612b05565b806001600160a01b03167f77f2d8afec4b9d82ffa0dea525320620292bd1067f575964994d5c4501479aed86868686604051610ca29493929190612e18565b60405180910390a25050505050565b60045481565b6000610d12610d016064610cf5610cd860208701358363ffffffff61172e16565b610ce988883563ffffffff61175316565b9063ffffffff61175316565b9063ffffffff61178d16565b60408401359063ffffffff61172e16565b90505b92915050565b6003543490811115610d3f5760405162461bcd60e51b815260040161040890612a5e565b6001600160a01b0382166000908152600c6020526040902054610d68908263ffffffff61172e16565b6001600160a01b0383166000818152600c6020526040908190209290925590513391907f8752a472e571a816aea92eec8dae9baf628e840f4929fbcc2d155e6233ff68a790610db89085906127e3565b60405180910390a35050565b60055481565b336000818152600b6020526040902080548301908190556007541015610e025760405162461bcd60e51b815260040161040890612b97565b610e0b81610b3f565b610e275760405162461bcd60e51b815260040161040890612a87565b60005b82811015610ef1576000600a81868685818110610e4357fe5b9050602002016020810190610e589190611f33565b6001600160a01b0390811682526020820192909252604001600020541614610e925760405162461bcd60e51b8152600401610408906128f7565b81600a6000868685818110610ea357fe5b9050602002016020810190610eb89190611f33565b6001600160a01b039081168252602082019290925260400160002080546001600160a01b03191692909116919091179055600101610e2a565b506001600160a01b0381166000818152600b6020526040908190205490517febf4a9bffb39f7c5dbf3f65540183b9381ae226ac3d0a45b4cad484713bd4a2891610f3e918791879161275f565b60405180910390a2505050565b6009546001600160a01b031681565b600a602052600090815260409020546001600160a01b031681565b6000805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610ffb5780601f10610fd057610100808354040283529160200191610ffb565b820191906000526020600020905b815481529060010190602001808311610fde57829003601f168201915b505050505081565b60075481565b6009546001600160a01b031633146110335760405162461bcd60e51b815260040161040890612b2f565b6001600160a01b038083166000908152600a6020526040902054168061106b5760405162461bcd60e51b815260040161040890612c87565b61107481610b3f565b6110905760405162461bcd60e51b815260040161040890612a87565b611098611d8d565b60085460405163c345315360e01b81526001600160a01b039091169063c3453153906110c890859060040161266a565b60806040518083038186803b1580156110e057600080fd5b505afa1580156110f4573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061111891906121be565b600854815160405163026822bd60e21b81529293506001600160a01b03909116916309a08af49161114f91869188916004016126cc565b600060405180830381600087803b15801561116957600080fd5b505af115801561117d573d6000803e3d6000fd5b5050505050505050565b60015481565b60065481565b6000606061119f611dbe565b3330146111be5760405162461bcd60e51b81526004016104089061292e565b600c60006111cf60208e018e612e94565b6111e09060a0810190608001611f33565b6001600160a01b0316815260208101919091526040908101600020548252516372e0922360e11b90611220908d908d908d908d908d908b90602401612dca565b60408051601f19818403018152919052602080820180516001600160e01b03166001600160e01b03199094169390931790925260a083015260009060609061126a908e018e612e94565b61127b9060a0810190608001611f33565b6001600160a01b031688602001358460a0015160405161129b9190612545565b60006040518083038160008787f1925050503d80600081146112d9576040519150601f19603f3d011682016040523d82523d6000602084013e6112de565b606091505b509092509050816112fd576112f2816117cf565b6112fd6002826117de565b80806020019051810190611311919061205e565b151560c08501526080840152506000905061132d8c8c8c611817565b60608501521515604084015290508061134f5761134f600383606001516117de565b8160c00151801561136257508160400151155b1561137657611376600483606001516117de565b50638e9483b060e01b816080015182604001515a88038e806020019061139c9190612e94565b6040516024016113af9493929190612862565b60408051601f19818403018152919052602080820180516001600160e01b03166001600160e01b03199094169390931790925260a08301526000906060906113f9908e018e612e94565b61140a9060a0810190608001611f33565b6001600160a01b031688604001358460a0015160405161142a9190612545565b60006040518083038160008787f1925050503d8060008114611468576040519150601f19603f3d011682016040523d82523d6000602084013e61146d565b606091505b509150915081611482576114826005826117de565b50508051600c600061149760208f018f612e94565b6114a89060a0810190608001611f33565b6001600160a01b03166001600160a01b031681526020019081526020016000205410156114e9576114e96006604051806020016040528060008152506117de565b80604001516114f95760016114fc565b60005b816060015192509250509850989650505050505050565b6000610d1283836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611a00565b6000816004018351101561157b5760405162461bcd60e51b815260040161040890612c50565b5001602001516001600160e01b03191690565b611596611df9565b60006115a56020850185612e94565b6115b69060a0810190608001611f33565b6001600160a01b0316635ea54eee61c3506040518263ffffffff1660e01b815260040160606040518083038187803b1580156115f157600080fd5b5086fa158015611605573d6000803e3d6000fd5b50505050506040513d601f19601f8201168201806040525081019061162a91906120c3565b805190925085101561164e5760405162461bcd60e51b8152600401610408906129d7565b61168c61165b8580612e7f565b606001356116808460400151611680866020015160045461172e90919063ffffffff16565b9063ffffffff61172e16565b9050808310156116ae5760405162461bcd60e51b815260040161040890612a0c565b60006116c1826102a86020880188612e94565b9050600c60006116d46020880188612e94565b6116e59060a0810190608001611f33565b6001600160a01b03166001600160a01b03168152602001908152602001600020548111156117255760405162461bcd60e51b815260040161040890612c19565b50935093915050565b600082820183811015610d125760405162461bcd60e51b815260040161040890612975565b60008261176257506000610d15565b8282028284828161176f57fe5b0414610d125760405162461bcd60e51b815260040161040890612b56565b6000610d1283836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611a2c565b6117db81610400611a63565b50565b606082826040516020016117f3929190612895565b604051602081830303815290604052905061180d816117cf565b8051602082018181fd5b6000806060611824611e1a565b606061182f88611a74565b9092509050600061185d61184660208b018b612e94565b6118589061010081019060e001611f33565b611b9e565b905061186c60208a018a612e94565b61187e9061010081019060e001611f33565b6001600160a01b031663cdf5735a60e01b84836040518060400160405280600c81526020016b14995b185e54995c5d595cdd60a21b8152506040518060800160405280604a815260200161303f604a91396040518060e0016040528060a18152602001612f9e60a191396040516020016118f891906125c4565b60408051601f1981840301815290829052611917939291602001612561565b60405160208183030381529060405280519060200120868d8d60405160240161194596959493929190612cb5565b60408051601f198184030181529181526020820180516001600160e01b03166001600160e01b03199094169390931790925290516119839190612545565b6000604051808303816000865af19150503d80600081146119c0576040519150601f19603f3d011682016040523d82523d6000602084013e6119c5565b606091505b50909650935085156119eb57838060200190518101906119e5919061200f565b90955093505b6119f4846117cf565b50505093509350939050565b60008184841115611a245760405162461bcd60e51b815260040161040891906128b6565b505050900390565b60008183611a4d5760405162461bcd60e51b815260040161040891906128b6565b506000838581611a5957fe5b0495945050505050565b8082511115611a70578082525b5050565b611a7c611e1a565b6040805160c0810190915260609080611a958580612e7f565b611aa3906020810190611f33565b6001600160a01b03168152602001611abb8580612e7f565b611acc906040810190602001611f33565b6001600160a01b03168152602001611ae48580612e7f565b604001358152602001611af78580612e7f565b606001358152602001611b0a8580612e7f565b608001358152602001611b1d8580612e7f565b611b2b9060a0810190612e38565b8080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525050509152509150611b78611b736020850185612e94565b611c1e565b604051602001611b8891906127e3565b6040516020818303038152906040529050915091565b6040805160c0810182526017608082019081527f47534e2052656c61796564205472616e73616374696f6e00000000000000000060a083015281528151808301835260018152601960f91b602082810191909152820152600091610bca91908101611c07611cd8565b8152602001846001600160a01b0316815250611cdc565b60006040518060e0016040528060a18152602001612f9e60a191398051602091820120908335908401356040850135611c5d6080870160608801611f33565b611c6d60a0880160808901611f33565b611c7e610100890160e08a01611f33565b611c8b60a08a018a612e38565b604051611c99929190612535565b604051908190038120611cbb989796959493929160c08c013590602001612818565b604051602081830303815290604052805190602001209050919050565b4690565b6000604051611cea90612600565b604051809103902082600001518051906020012083602001518051906020012084604001518560600151604051602001611cbb9594939291906127ec565b60405180610140016040528060001515815260200160006001600160e01b03191681526020016060815260200160608152602001611d64611df9565b815260200160008152602001600081526020016000815260200160008152602001606081525090565b604051806080016040528060008152602001600081526020016000815260200160006001600160a01b031681525090565b6040805160e08101825260008082526020820181905291810182905260608082018190526080820181905260a082015260c081019190915290565b60405180606001604052806000815260200160008152602001600081525090565b6040518060c0016040528060006001600160a01b0316815260200160006001600160a01b03168152602001600081526020016000815260200160008152602001606081525090565b8035610d1581612f7a565b60008083601f840112611e7e578182fd5b50813567ffffffffffffffff811115611e95578182fd5b602083019150836020828501011115611ead57600080fd5b9250929050565b600082601f830112611ec4578081fd5b815167ffffffffffffffff811115611eda578182fd5b611eed601f8201601f1916602001612ea9565b9150808252836020828501011115611f0457600080fd5b611f15816020840160208601612f4a565b5092915050565b600060408284031215611f2d578081fd5b50919050565b600060208284031215611f44578081fd5b8135610d1281612f7a565b60008060408385031215611f61578081fd5b8235611f6c81612f7a565b91506020830135611f7c81612f7a565b809150509250929050565b60008060208385031215611f99578182fd5b823567ffffffffffffffff80821115611fb0578384fd5b81850186601f820112611fc1578485fd5b8035925081831115611fd1578485fd5b8660208085028301011115611fe4578485fd5b60200196919550909350505050565b600060208284031215612004578081fd5b8151610d1281612f8f565b60008060408385031215612021578182fd5b825161202c81612f8f565b602084015190925067ffffffffffffffff811115612048578182fd5b61205485828601611eb4565b9150509250929050565b60008060408385031215612070578182fd5b825167ffffffffffffffff811115612086578283fd5b61209285828601611eb4565b9250506020830151611f7c81612f8f565b600080604083850312156120b5578182fd5b82516007811061202c578283fd5b6000606082840312156120d4578081fd5b6120de6060612ea9565b8251815260208301516020820152604083015160408201528091505092915050565b600080600080600080600080888a0361010081121561211d578485fd5b893567ffffffffffffffff80821115612134578687fd5b6121408d838e01611f1c565b9a5060208c0135915080821115612155578687fd5b6121618d838e01611e6d565b909a50985060408c0135915080821115612179578687fd5b506121868c828d01611e6d565b9097509550506060605f198201121561219d578384fd5b5096999598509396929550909360608301935060c08301359260e001359150565b6000608082840312156121cf578081fd5b6121d96080612ea9565b82518152602083015160208201526040830151604082015260608301516121ff81612f7a565b60608201529392505050565b6000806040838503121561221d578182fd5b823591506020830135611f7c81612f7a565b60008060408385031215612241578182fd5b82359150602083013567ffffffffffffffff81111561225e578182fd5b8084016101008187031215612271578283fd5b80925050509250929050565b600080600080600080600060a0888a031215612297578081fd5b87359650602088013567ffffffffffffffff808211156122b5578283fd5b6122c18b838c01611f1c565b975060408a01359150808211156122d6578283fd5b6122e28b838c01611e6d565b909750955060608a01359150808211156122fa578283fd5b506123078a828b01611e6d565b989b979a50959894979596608090950135949350505050565b60008060008060608587031215612335578182fd5b8435935060208501359250604085013567ffffffffffffffff811115612359578283fd5b61236587828801611e6d565b95989497509550505050565b6001600160a01b03169052565b60008284528282602086013780602084860101526020601f19601f85011685010190509392505050565b600081518084526123c0816020860160208601612f4a565b601f01601f19169290920160200192915050565b600061010082358452602083013560208501526040830135604085015260608301356123ff81612f7a565b6001600160a01b03908116606086015260808401359061241e82612f7a565b16608085015261243160a0840184612ed0565b8260a0870152612444838701828461237e565b60c086013560c088015260e0860135935061245e84612f7a565b61246b60e0880185612371565b9695505050505050565b6000813560be1983360301811261248a578182fd5b60408452820180359061249c82612f7a565b6001600160a01b03918216604086810191909152810191806124c18460208501611e62565b1660608701525081356080860152606081013560a0860152608081013560c08601526124f060a0820182612ed0565b925060c060e08701526125086101008701848361237e565b9150506125186020850185612f15565b9150848103602086015261252c81836123d4565b95945050505050565b6000828483379101908152919050565b60008251612557818460208701612f4a565b9190910192915050565b60008451612573818460208901612f4a565b808301600560fb1b815285519150612592826001830160208901612f4a565b818101600b60fa1b6001820152855192506125b4836002830160208901612f4a565b9091016002019695505050505050565b60007352656c6179446174612072656c6179446174612960601b825282516125f3816014850160208701612f4a565b9190910160140192915050565b7f454950373132446f6d61696e28737472696e67206e616d652c737472696e672081527f76657273696f6e2c75696e7432353620636861696e49642c6164647265737320602082015271766572696679696e67436f6e74726163742960701b604082015260520190565b6001600160a01b0391909116815260200190565b6001600160a01b038681168252851660208201526001600160e01b0319841660408201526060810183905260a0608082018190526000906126c1908301846123a8565b979650505050505050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b038681168252851660208201526001600160e01b03198416604082015260a0810161272184612f3f565b60608301528260808301529695505050505050565b6001600160a01b0394851681529290931660208301526040820152606081019190915260800190565b6040808252810183905260008460608301825b868110156127a2576020833561278781612f7a565b6001600160a01b031683529283019290910190600101612772565b5060209390930193909352509392505050565b901515815260200190565b60008315158252604060208301526127db60408301846123a8565b949350505050565b90815260200190565b9485526020850193909352604084019190915260608301526001600160a01b0316608082015260a00190565b9889526020890197909752604088019590955260608701939093526001600160a01b039182166080870152811660a08601521660c084015260e08301526101008201526101200190565b60006080825261287560808301876123a8565b851515602084015284604084015282810360608401526126c181856123d4565b60006128a084612f3f565b8252604060208301526127db60408301846123a8565b600060208252610d1260208301846123a8565b602080825260149082015273125b5c1bdcdcda589b194819d85cc81b1a5b5a5d60621b604082015260600190565b60208082526019908201527f7468697320776f726b6572206861732061206d616e6167657200000000000000604082015260600190565b60208082526027908201527f4f6e6c792052656c61794875622073686f756c642063616c6c207468697320666040820152663ab731ba34b7b760c91b606082015260800190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b602080825260119082015270496e76616c69642067617320707269636560781b604082015260600190565b6020808252818101527f756e6578706563746564206869676820616363657074616e6365427564676574604082015260600190565b60208082526032908201527f4e6f7420656e6f75676820676173206c65667420666f7220696e6e657252656c604082015271617943616c6c20746f20636f6d706c65746560701b606082015260800190565b6020808252600f908201526e6465706f73697420746f6f2062696760881b604082015260600190565b60208082526018908201527f72656c6179206d616e61676572206e6f74207374616b65640000000000000000604082015260600190565b60208082526027908201527f72656c617920776f726b65722063616e6e6f74206265206120736d61727420636040820152661bdb9d1c9858dd60ca1b606082015260800190565b60208082526010908201526f6e6f2072656c617920776f726b65727360801b604082015260600190565b6020808252600d908201526c2737ba103832b730b634bd32b960991b604082015260600190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526010908201526f746f6f206d616e7920776f726b65727360801b604082015260600190565b602080825260129082015271696e73756666696369656e742066756e647360701b604082015260600190565b6020808252601290820152712737ba1030903934b3b43a103bb7b935b2b960711b604082015260600190565b60208082526019908201527f5061796d61737465722062616c616e636520746f6f206c6f7700000000000000604082015260600190565b6020808252601a908201527f726561644279746573343a206461746120746f6f2073686f7274000000000000604082015260600190565b6020808252601490820152732ab735b737bbb7103932b630bc903bb7b935b2b960611b604082015260600190565b600060a08252612cc58851612f33565b60a083015260018060a01b0360208901511660c0830152604088015160e08301526060880151610100830152608088015161012083015260a088015160c0610140840152612d176101608401826123a8565b8860208501528760408501528381036060850152612d3581886123a8565b9150508281036080840152612d4b81858761237e565b9998505050505050505050565b6000610100808352612d6c8184018c612475565b8381036020850152612d7f818b8d61237e565b9150508281036040840152612d9581888a61237e565b865160608501526020870151608085015260409096015160a0840152505060c081019290925260e09091015295945050505050565b600060808252612ddd6080830189612475565b8281036020840152612df081888a61237e565b8381036040850152612e0381878961237e565b92505050826060830152979650505050505050565b60008582528460208301526060604083015261246b60608301848661237e565b6000808335601e19843603018112612e4e578283fd5b8084018035925067ffffffffffffffff831115612e69578384fd5b60200192505036819003821315611ead57600080fd5b6000823560be19833603018112612557578182fd5b6000823560fe19833603018112612557578182fd5b60405181810167ffffffffffffffff81118282101715612ec857600080fd5b604052919050565b6000808335601e19843603018112612ee6578283fd5b830160208101925035905067ffffffffffffffff811115612f0657600080fd5b803603831315611ead57600080fd5b6000823560fe19833603018112612f2a578182fd5b90910192915050565b6001600160a01b031690565b8060078110610bcd57fe5b60005b83811015612f65578181015183820152602001612f4d565b83811115612f74576000848401525b50505050565b6001600160a01b03811681146117db57600080fd5b80151581146117db57600080fdfe52656c6179446174612875696e743235362067617350726963652c75696e743235362070637452656c61794665652c75696e74323536206261736552656c61794665652c616464726573732072656c6179576f726b65722c61646472657373207061796d61737465722c6164647265737320666f727761726465722c6279746573207061796d6173746572446174612c75696e7432353620636c69656e74496429616464726573732066726f6d2c6164647265737320746f2c75696e743235362076616c75652c75696e74323536206761732c75696e74323536206e6f6e63652c62797465732064617461a2646970667358221220ee76ddcfb577a3edcb3ac659f9e36efe7f00c80d161c4f13e4d8b473488c840564736f6c634300060a0033
[ 0, 7, 11, 9, 12, 5, 2 ]
0x51be9f12dd5095c5b1acf90e7e0aa4aa8023218b
pragma solidity 0.6.2; 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract ERC20FixedSupply is ERC20 { constructor() public ERC20("Dacxi Gold Token", "DXGT") { _mint(msg.sender, 100000 * 1e18); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b6106778560405180606001604052806028815260200161102660289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161109760259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110736024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fde6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061104e6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fbb6023913960400191505060405180910390fd5b610cc3838383610fb5565b610d2e81604051806060016040528060268152602001611000602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610dc1816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f1a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610edf578082015181840152602081019050610ec4565b50505050905090810190601f168015610f0c5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fab576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220cb6183a4c968177e8ce5b5ef350b88b0684e3a0e18372d36101addf2cbb6d88564736f6c63430006020033
[ 38 ]
0x5262aa93f471628efe57151480b78bee17e9b48c
pragma solidity 0.4.18; interface ConversionRatesInterface { function recordImbalance( ERC20 token, int buyAmount, uint rateUpdateBlock, uint currentBlock ) public; function getRate(ERC20 token, uint currentBlockNumber, bool buy, uint qty) public view returns(uint); } interface ERC20 { function totalSupply() public view returns (uint supply); function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); function decimals() public view returns(uint digits); event Approval(address indexed _owner, address indexed _spender, uint _value); } contract UtilMath { uint public constant BIG_NUMBER = (uint(1)<<uint(200)); function checkMultOverflow(uint x, uint y) public pure returns(bool) { if (y == 0) return false; return (((x*y) / y) != x); } function compactFraction(uint p, uint q, uint precision) public pure returns (uint, uint) { if (q < precision * precision) return (p, q); return compactFraction(p/precision, q/precision, precision); } /* solhint-disable code-complexity */ function exp(uint p, uint q, uint precision) public pure returns (uint) { uint n = 0; uint nFact = 1; uint currentP = 1; uint currentQ = 1; uint sum = 0; uint prevSum = 0; while (true) { if (checkMultOverflow(currentP, precision)) return sum; if (checkMultOverflow(currentQ, nFact)) return sum; sum += (currentP * precision) / (currentQ * nFact); if (sum == prevSum) return sum; prevSum = sum; n++; if (checkMultOverflow(currentP, p)) return sum; if (checkMultOverflow(currentQ, q)) return sum; if (checkMultOverflow(nFact, n)) return sum; currentP *= p; currentQ *= q; nFact *= n; (currentP, currentQ) = compactFraction(currentP, currentQ, precision); } } /* solhint-enable code-complexity */ function countLeadingZeros(uint p, uint q) public pure returns (uint) { uint denomator = (uint(1)<<255); for (int i = 255; i >= 0; i--) { if ((q*denomator)/denomator != q) { // overflow denomator = denomator/2; continue; } if (p/(q*denomator) > 0) return uint(i); denomator = denomator/2; } return uint(-1); } // log2 for a number that it in [1,2) function log2ForSmallNumber(uint x, uint numPrecisionBits) public pure returns (uint) { uint res = 0; uint one = (uint(1)<<numPrecisionBits); uint two = 2 * one; uint addition = one; require((x >= one) && (x <= two)); require(numPrecisionBits < 125); for (uint i = numPrecisionBits; i > 0; i--) { x = (x*x) / one; addition = addition/2; if (x >= two) { x = x/2; res += addition; } } return res; } function logBase2 (uint p, uint q, uint numPrecisionBits) public pure returns (uint) { uint n = 0; uint precision = (uint(1)<<numPrecisionBits); if (p > q) { n = countLeadingZeros(p, q); } require(!checkMultOverflow(p, precision)); require(!checkMultOverflow(n, precision)); require(!checkMultOverflow(uint(1)<<n, q)); uint y = p * precision / (q * (uint(1)<<n)); uint log2Small = log2ForSmallNumber(y, numPrecisionBits); require(n*precision <= BIG_NUMBER); require(log2Small <= BIG_NUMBER); return n * precision + log2Small; } function ln(uint p, uint q, uint numPrecisionBits) public pure returns (uint) { uint ln2Numerator = 6931471805599453094172; uint ln2Denomerator = 10000000000000000000000; uint log2x = logBase2(p, q, numPrecisionBits); require(!checkMultOverflow(ln2Numerator, log2x)); return ln2Numerator * log2x / ln2Denomerator; } } contract LiquidityFormula is UtilMath { function pE(uint r, uint pMIn, uint e, uint precision) public pure returns (uint) { require(!checkMultOverflow(r, e)); uint expRE = exp(r*e, precision*precision, precision); require(!checkMultOverflow(expRE, pMIn)); return pMIn*expRE / precision; } function deltaTFunc(uint r, uint pMIn, uint e, uint deltaE, uint precision) public pure returns (uint) { uint pe = pE(r, pMIn, e, precision); uint rpe = r * pe; require(!checkMultOverflow(r, deltaE)); uint erdeltaE = exp(r*deltaE, precision*precision, precision); require(erdeltaE >= precision); require(!checkMultOverflow(erdeltaE - precision, precision)); require(!checkMultOverflow((erdeltaE - precision)*precision, precision)); require(!checkMultOverflow((erdeltaE - precision)*precision*precision, precision)); require(!checkMultOverflow(rpe, erdeltaE)); require(!checkMultOverflow(r, pe)); return (erdeltaE - precision) * precision * precision * precision / (rpe*erdeltaE); } function deltaEFunc(uint r, uint pMIn, uint e, uint deltaT, uint precision, uint numPrecisionBits) public pure returns (uint) { uint pe = pE(r, pMIn, e, precision); uint rpe = r * pe; require(!checkMultOverflow(rpe, deltaT)); require(precision * precision + rpe * deltaT/precision > precision * precision); uint lnPart = ln(precision*precision + rpe*deltaT/precision, precision*precision, numPrecisionBits); require(!checkMultOverflow(r, pe)); require(!checkMultOverflow(precision, precision)); require(!checkMultOverflow(rpe, deltaT)); require(!checkMultOverflow(lnPart, precision)); return lnPart * precision / r; } } contract PermissionGroups { address public admin; address public pendingAdmin; mapping(address=>bool) internal operators; mapping(address=>bool) internal alerters; address[] internal operatorsGroup; address[] internal alertersGroup; uint constant internal MAX_GROUP_SIZE = 50; function PermissionGroups() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier onlyOperator() { require(operators[msg.sender]); _; } modifier onlyAlerter() { require(alerters[msg.sender]); _; } function getOperators () external view returns(address[]) { return operatorsGroup; } function getAlerters () external view returns(address[]) { return alertersGroup; } event TransferAdminPending(address pendingAdmin); /** * @dev Allows the current admin to set the pendingAdmin address. * @param newAdmin The address to transfer ownership to. */ function transferAdmin(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(pendingAdmin); pendingAdmin = newAdmin; } /** * @dev Allows the current admin to set the admin in one tx. Useful initial deployment. * @param newAdmin The address to transfer ownership to. */ function transferAdminQuickly(address newAdmin) public onlyAdmin { require(newAdmin != address(0)); TransferAdminPending(newAdmin); AdminClaimed(newAdmin, admin); admin = newAdmin; } event AdminClaimed( address newAdmin, address previousAdmin); /** * @dev Allows the pendingAdmin address to finalize the change admin process. */ function claimAdmin() public { require(pendingAdmin == msg.sender); AdminClaimed(pendingAdmin, admin); admin = pendingAdmin; pendingAdmin = address(0); } event AlerterAdded (address newAlerter, bool isAdd); function addAlerter(address newAlerter) public onlyAdmin { require(!alerters[newAlerter]); // prevent duplicates. require(alertersGroup.length < MAX_GROUP_SIZE); AlerterAdded(newAlerter, true); alerters[newAlerter] = true; alertersGroup.push(newAlerter); } function removeAlerter (address alerter) public onlyAdmin { require(alerters[alerter]); alerters[alerter] = false; for (uint i = 0; i < alertersGroup.length; ++i) { if (alertersGroup[i] == alerter) { alertersGroup[i] = alertersGroup[alertersGroup.length - 1]; alertersGroup.length--; AlerterAdded(alerter, false); break; } } } event OperatorAdded(address newOperator, bool isAdd); function addOperator(address newOperator) public onlyAdmin { require(!operators[newOperator]); // prevent duplicates. require(operatorsGroup.length < MAX_GROUP_SIZE); OperatorAdded(newOperator, true); operators[newOperator] = true; operatorsGroup.push(newOperator); } function removeOperator (address operator) public onlyAdmin { require(operators[operator]); operators[operator] = false; for (uint i = 0; i < operatorsGroup.length; ++i) { if (operatorsGroup[i] == operator) { operatorsGroup[i] = operatorsGroup[operatorsGroup.length - 1]; operatorsGroup.length -= 1; OperatorAdded(operator, false); break; } } } } contract Utils { ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); uint constant internal PRECISION = (10**18); uint constant internal MAX_QTY = (10**28); // 10B tokens uint constant internal MAX_RATE = (PRECISION * 10**6); // up to 1M tokens per ETH uint constant internal MAX_DECIMALS = 18; uint constant internal ETH_DECIMALS = 18; mapping(address=>uint) internal decimals; function setDecimals(ERC20 token) internal { if (token == ETH_TOKEN_ADDRESS) decimals[token] = ETH_DECIMALS; else decimals[token] = token.decimals(); } function getDecimals(ERC20 token) internal view returns(uint) { if (token == ETH_TOKEN_ADDRESS) return ETH_DECIMALS; // save storage access uint tokenDecimals = decimals[token]; // technically, there might be token with decimals 0 // moreover, very possible that old tokens have decimals 0 // these tokens will just have higher gas fees. if(tokenDecimals == 0) return token.decimals(); return tokenDecimals; } function calcDstQty(uint srcQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(srcQty <= MAX_QTY); require(rate <= MAX_RATE); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (srcQty * rate * (10**(dstDecimals - srcDecimals))) / PRECISION; } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (srcQty * rate) / (PRECISION * (10**(srcDecimals - dstDecimals))); } } function calcSrcQty(uint dstQty, uint srcDecimals, uint dstDecimals, uint rate) internal pure returns(uint) { require(dstQty <= MAX_QTY); require(rate <= MAX_RATE); //source quantity is rounded up. to avoid dest quantity being too low. uint numerator; uint denominator; if (srcDecimals >= dstDecimals) { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty * (10**(srcDecimals - dstDecimals))); denominator = rate; } else { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); numerator = (PRECISION * dstQty); denominator = (rate * (10**(dstDecimals - srcDecimals))); } return (numerator + denominator - 1) / denominator; //avoid rounding down errors } } contract Withdrawable is PermissionGroups { event TokenWithdraw(ERC20 token, uint amount, address sendTo); /** * @dev Withdraw all ERC20 compatible tokens * @param token ERC20 The address of the token contract */ function withdrawToken(ERC20 token, uint amount, address sendTo) external onlyAdmin { require(token.transfer(sendTo, amount)); TokenWithdraw(token, amount, sendTo); } event EtherWithdraw(uint amount, address sendTo); /** * @dev Withdraw Ethers */ function withdrawEther(uint amount, address sendTo) external onlyAdmin { sendTo.transfer(amount); EtherWithdraw(amount, sendTo); } } contract LiquidityConversionRates is ConversionRatesInterface, LiquidityFormula, Withdrawable, Utils { uint constant FORMULA_PRECISION_BITS = 40; ERC20 public token; address public reserveContract; uint public numFpBits; uint public formulaPrecision; uint public rInFp; uint public pMinInFp; uint public maxEthCapBuyInFp; uint public maxEthCapSellInFp; uint public maxQtyInFp; uint public feeInBps; uint public collectedFeesInTwei = 0; uint public maxBuyRateInPrecision; uint public minBuyRateInPrecision; uint public maxSellRateInPrecision; uint public minSellRateInPrecision; function LiquidityConversionRates(address _admin, ERC20 _token) public { transferAdminQuickly(_admin); token = _token; setDecimals(token); require(getDecimals(token) <= MAX_DECIMALS); } event ReserveAddressSet(address reserve); function setReserveAddress(address reserve) public onlyAdmin { reserveContract = reserve; ReserveAddressSet(reserve); } event LiquidityParamsSet( uint rInFp, uint pMinInFp, uint numFpBits, uint maxCapBuyInFp, uint maxEthCapSellInFp, uint feeInBps, uint formulaPrecision, uint maxQtyInFp, uint maxBuyRateInPrecision, uint minBuyRateInPrecision, uint maxSellRateInPrecision, uint minSellRateInPrecision ); function setLiquidityParams( uint _rInFp, uint _pMinInFp, uint _numFpBits, uint _maxCapBuyInWei, uint _maxCapSellInWei, uint _feeInBps, uint _maxTokenToEthRateInPrecision, uint _minTokenToEthRateInPrecision ) public onlyAdmin { require(_numFpBits == FORMULA_PRECISION_BITS); // only used config, but keep in API formulaPrecision = uint(1)<<_numFpBits; // require(formulaPrecision <= MAX_QTY) require(_feeInBps < 10000); require(_minTokenToEthRateInPrecision < _maxTokenToEthRateInPrecision); require(_minTokenToEthRateInPrecision > 0); require(_rInFp > 0); require(_pMinInFp > 0); rInFp = _rInFp; pMinInFp = _pMinInFp; maxQtyInFp = fromWeiToFp(MAX_QTY); numFpBits = _numFpBits; maxEthCapBuyInFp = fromWeiToFp(_maxCapBuyInWei); maxEthCapSellInFp = fromWeiToFp(_maxCapSellInWei); feeInBps = _feeInBps; maxBuyRateInPrecision = PRECISION * PRECISION / _minTokenToEthRateInPrecision; minBuyRateInPrecision = PRECISION * PRECISION / _maxTokenToEthRateInPrecision; maxSellRateInPrecision = _maxTokenToEthRateInPrecision; minSellRateInPrecision = _minTokenToEthRateInPrecision; LiquidityParamsSet( rInFp, pMinInFp, numFpBits, maxEthCapBuyInFp, maxEthCapSellInFp, feeInBps, formulaPrecision, maxQtyInFp, maxBuyRateInPrecision, minBuyRateInPrecision, maxSellRateInPrecision, minSellRateInPrecision ); } function recordImbalance( ERC20 conversionToken, int buyAmountInTwei, uint rateUpdateBlock, uint currentBlock ) public { conversionToken; rateUpdateBlock; currentBlock; require(msg.sender == reserveContract); if (buyAmountInTwei > 0) { // Buy case collectedFeesInTwei += calcCollectedFee(abs(buyAmountInTwei)); } else { // Sell case collectedFeesInTwei += abs(buyAmountInTwei) * feeInBps / 10000; } } event CollectedFeesReset(uint resetFeesInTwei); function resetCollectedFees() public onlyAdmin { uint resetFeesInTwei = collectedFeesInTwei; collectedFeesInTwei = 0; CollectedFeesReset(resetFeesInTwei); } function getRate( ERC20 conversionToken, uint currentBlockNumber, bool buy, uint qtyInSrcWei ) public view returns(uint) { currentBlockNumber; require(qtyInSrcWei <= MAX_QTY); uint eInFp = fromWeiToFp(reserveContract.balance); uint rateInPrecision = getRateWithE(conversionToken, buy, qtyInSrcWei, eInFp); require(rateInPrecision <= MAX_RATE); return rateInPrecision; } function getRateWithE(ERC20 conversionToken, bool buy, uint qtyInSrcWei, uint eInFp) public view returns(uint) { uint deltaEInFp; uint sellInputTokenQtyInFp; uint deltaTInFp; uint rateInPrecision; require(qtyInSrcWei <= MAX_QTY); require(eInFp <= maxQtyInFp); if (conversionToken != token) return 0; if (buy) { // ETH goes in, token goes out deltaEInFp = fromWeiToFp(qtyInSrcWei); if (deltaEInFp > maxEthCapBuyInFp) return 0; if (deltaEInFp == 0) { rateInPrecision = buyRateZeroQuantity(eInFp); } else { rateInPrecision = buyRate(eInFp, deltaEInFp); } } else { sellInputTokenQtyInFp = fromTweiToFp(qtyInSrcWei); deltaTInFp = valueAfterReducingFee(sellInputTokenQtyInFp); if (deltaTInFp == 0) { rateInPrecision = sellRateZeroQuantity(eInFp); deltaEInFp = 0; } else { (rateInPrecision, deltaEInFp) = sellRate(eInFp, sellInputTokenQtyInFp, deltaTInFp); } if (deltaEInFp > maxEthCapSellInFp) return 0; } rateInPrecision = rateAfterValidation(rateInPrecision, buy); return rateInPrecision; } function rateAfterValidation(uint rateInPrecision, bool buy) public view returns(uint) { uint minAllowRateInPrecision; uint maxAllowedRateInPrecision; if (buy) { minAllowRateInPrecision = minBuyRateInPrecision; maxAllowedRateInPrecision = maxBuyRateInPrecision; } else { minAllowRateInPrecision = minSellRateInPrecision; maxAllowedRateInPrecision = maxSellRateInPrecision; } if ((rateInPrecision > maxAllowedRateInPrecision) || (rateInPrecision < minAllowRateInPrecision)) { return 0; } else if (rateInPrecision > MAX_RATE) { return 0; } else { return rateInPrecision; } } function buyRate(uint eInFp, uint deltaEInFp) public view returns(uint) { uint deltaTInFp = deltaTFunc(rInFp, pMinInFp, eInFp, deltaEInFp, formulaPrecision); require(deltaTInFp <= maxQtyInFp); deltaTInFp = valueAfterReducingFee(deltaTInFp); return deltaTInFp * PRECISION / deltaEInFp; } function buyRateZeroQuantity(uint eInFp) public view returns(uint) { uint ratePreReductionInPrecision = formulaPrecision * PRECISION / pE(rInFp, pMinInFp, eInFp, formulaPrecision); return valueAfterReducingFee(ratePreReductionInPrecision); } function sellRate( uint eInFp, uint sellInputTokenQtyInFp, uint deltaTInFp ) public view returns(uint rateInPrecision, uint deltaEInFp) { deltaEInFp = deltaEFunc(rInFp, pMinInFp, eInFp, deltaTInFp, formulaPrecision, numFpBits); require(deltaEInFp <= maxQtyInFp); rateInPrecision = deltaEInFp * PRECISION / sellInputTokenQtyInFp; } function sellRateZeroQuantity(uint eInFp) public view returns(uint) { uint ratePreReductionInPrecision = pE(rInFp, pMinInFp, eInFp, formulaPrecision) * PRECISION / formulaPrecision; return valueAfterReducingFee(ratePreReductionInPrecision); } function fromTweiToFp(uint qtyInTwei) public view returns(uint) { require(qtyInTwei <= MAX_QTY); return qtyInTwei * formulaPrecision / (10 ** getDecimals(token)); } function fromWeiToFp(uint qtyInwei) public view returns(uint) { require(qtyInwei <= MAX_QTY); return qtyInwei * formulaPrecision / (10 ** ETH_DECIMALS); } function valueAfterReducingFee(uint val) public view returns(uint) { require(val <= BIG_NUMBER); return ((10000 - feeInBps) * val) / 10000; } function calcCollectedFee(uint val) public view returns(uint) { require(val <= MAX_QTY); return val * feeInBps / (10000 - feeInBps); } function abs(int val) public pure returns(uint) { if (val < 0) { return uint(val * (-1)); } else { return uint(val); } } }
0x6060604052600436106102795763ffffffff60e060020a60003504166301a12fd3811461027e5780630f9b51291461029f57806314673d31146102c45780631b5ac4b5146102e35780631f05ff29146102f957806320b0961c1461030f578063267822471461032e578063275acbe31461035d578063279fe9671461037957806327a099d81461038c5780632f4fda30146103f25780633ccdbb2814610405578063402776041461042e578063408ee7fe14610441578063436f64ac14610460578063463cf7301461047357806347be7bce146104865780634857d52d146104995780635111249e146104c45780635909e897146104f1578063625cfc461461050a5780636f3d80431461052057806371f805bf1461053657806375829def1461054957806377f50f97146105685780637acc86781461057b5780637c423f541461059a57806382f19e3a146105ad5780638369ff08146105cf5780638401824f146105e8578063859618641461061c578063869d7d9314610646578063925176d61461065f578063958186031461067b5780639870d7fe14610691578063a0099b60146106b0578063a0a7299b146106d5578063a0dbde9d146106e8578063a2c99d4714610704578063a7f43acd1461071f578063aa98d57b14610732578063ac8a584a14610748578063b5debaf514610767578063b86f6aa714610783578063b8e9c22e14610796578063c6fd2103146107c0578063ce56c454146107e8578063debc74f61461080a578063e255d5ad14610820578063e570270114610833578063ec6b16ca14610846578063f0247f7814610859578063f851a4401461086c578063fbe3462c1461087f578063fc0c546a14610892575b600080fd5b341561028957600080fd5b61029d600160a060020a03600435166108a5565b005b34156102aa57600080fd5b6102b2610a15565b60405190815260200160405180910390f35b34156102cf57600080fd5b61029d600160a060020a0360043516610a1b565b34156102ee57600080fd5b6102b2600435610a91565b341561030457600080fd5b6102b2600435610aae565b341561031a57600080fd5b6102b2600435602435604435606435610ae0565b341561033957600080fd5b610341610b34565b604051600160a060020a03909116815260200160405180910390f35b341561036857600080fd5b6102b2600435602435604435610b43565b341561038457600080fd5b6102b2610b96565b341561039757600080fd5b61039f610b9c565b60405160208082528190810183818151815260200191508051906020019060200280838360005b838110156103de5780820151838201526020016103c6565b505050509050019250505060405180910390f35b34156103fd57600080fd5b6102b2610c05565b341561041057600080fd5b61029d600160a060020a036004358116906024359060443516610c0d565b341561043957600080fd5b6102b2610d04565b341561044c57600080fd5b61029d600160a060020a0360043516610d0a565b341561046b57600080fd5b6102b2610e06565b341561047e57600080fd5b6102b2610e0c565b341561049157600080fd5b6102b2610e12565b34156104a457600080fd5b61029d60043560243560443560643560843560a43560c43560e435610e18565b34156104cf57600080fd5b6104dd600435602435610fc2565b604051901515815260200160405180910390f35b34156104fc57600080fd5b6102b2600435602435610fed565b341561051557600080fd5b6102b260043561103e565b341561052b57600080fd5b6102b260043561107e565b341561054157600080fd5b6102b26110a1565b341561055457600080fd5b61029d600160a060020a03600435166110a7565b341561057357600080fd5b61029d611142565b341561058657600080fd5b61029d600160a060020a03600435166111dc565b34156105a557600080fd5b61039f6112be565b34156105b857600080fd5b6102b2600435602435604435606435608435611324565b34156105da57600080fd5b6102b2600435602435611402565b34156105f357600080fd5b610604600435602435604435611480565b60405191825260208201526040908101905180910390f35b341561062757600080fd5b6102b2600160a060020a036004351660243515156044356064356114c5565b341561065157600080fd5b6102b26004356024356115ce565b341561066a57600080fd5b610604600435602435604435611657565b341561068657600080fd5b6102b26004356116a2565b341561069c57600080fd5b61029d600160a060020a03600435166116e3565b34156106bb57600080fd5b6102b260043560243560443560643560843560a4356117b3565b34156106e057600080fd5b6102b261188d565b34156106f357600080fd5b6102b2600435602435604435611893565b341561070f57600080fd5b6102b26004356024351515611946565b341561072a57600080fd5b6103416119a5565b341561073d57600080fd5b6102b26004356119b4565b341561075357600080fd5b61029d600160a060020a03600435166119e4565b341561077257600080fd5b6102b2600435602435604435611b50565b341561078e57600080fd5b61029d611c27565b34156107a157600080fd5b6102b2600160a060020a03600435166024356044351515606435611c83565b34156107cb57600080fd5b61029d600160a060020a0360043516602435604435606435611ce7565b34156107f357600080fd5b61029d600435600160a060020a0360243516611d57565b341561081557600080fd5b6102b2600435611dea565b341561082b57600080fd5b6102b2611e15565b341561083e57600080fd5b6102b2611e1b565b341561085157600080fd5b6102b2611e21565b341561086457600080fd5b6102b2611e27565b341561087757600080fd5b610341611e2d565b341561088a57600080fd5b6102b2611e3c565b341561089d57600080fd5b610341611e42565b6000805433600160a060020a039081169116146108c157600080fd5b600160a060020a03821660009081526003602052604090205460ff1615156108e857600080fd5b50600160a060020a0381166000908152600360205260408120805460ff191690555b600554811015610a115781600160a060020a031660058281548110151561092d57fe5b600091825260209091200154600160a060020a03161415610a095760058054600019810190811061095a57fe5b60009182526020909120015460058054600160a060020a03909216918390811061098057fe5b60009182526020909120018054600160a060020a031916600160a060020a039290921691909117905560058054906109bc906000198301611f0b565b507f5611bf3e417d124f97bf2c788843ea8bb502b66079fbee02158ef30b172cb762826000604051600160a060020a039092168252151560208201526040908101905180910390a1610a11565b60010161090a565b5050565b60145481565b60005433600160a060020a03908116911614610a3657600080fd5b60088054600160a060020a031916600160a060020a0383161790557fbd2ca09dd2b354751631db75d1a63231ec123c0d68c81928ea03d0be326c7f8881604051600160a060020a03909116815260200160405180910390a150565b600080821215610aa657506000198102610aa9565b50805b919050565b60006b204fce5e3e25026110000000821115610ac957600080fd5b600a54670de0b6b3a76400009083025b0492915050565b600080610aed8685610fc2565b15610af757600080fd5b610b0684870284850285611b50565b9050610b128186610fc2565b15610b1c57600080fd5b82818602811515610b2957fe5b049695505050505050565b600154600160a060020a031681565b6000690177c17eb2ae5edd211c69021e19e0c9bab240000082610b67878787611893565b9050610b738382610fc2565b15610b7d57600080fd5b81818402811515610b8a57fe5b04979650505050505050565b600e5481565b610ba4611f34565b6004805480602002602001604051908101604052809291908181526020018280548015610bfa57602002820191906000526020600020905b8154600160a060020a03168152600190910190602001808311610bdc575b505050505090505b90565b60c860020a81565b60005433600160a060020a03908116911614610c2857600080fd5b82600160a060020a031663a9059cbb828460006040516020015260405160e060020a63ffffffff8516028152600160a060020a0390921660048301526024820152604401602060405180830381600087803b1515610c8557600080fd5b6102c65a03f11515610c9657600080fd5b505050604051805190501515610cab57600080fd5b7f72cb8a894ddb372ceec3d2a7648d86f17d5a15caae0e986c53109b8a9a9385e6838383604051600160a060020a03938416815260208101929092529091166040808301919091526060909101905180910390a1505050565b60115481565b60005433600160a060020a03908116911614610d2557600080fd5b600160a060020a03811660009081526003602052604090205460ff1615610d4b57600080fd5b60055460329010610d5b57600080fd5b7f5611bf3e417d124f97bf2c788843ea8bb502b66079fbee02158ef30b172cb762816001604051600160a060020a039092168252151560208201526040908101905180910390a1600160a060020a0381166000908152600360205260409020805460ff191660019081179091556005805490918101610dda8382611f0b565b5060009182526020909120018054600160a060020a031916600160a060020a0392909216919091179055565b600b5481565b600d5481565b600a5481565b60005433600160a060020a03908116911614610e3357600080fd5b60288614610e4057600080fd5b600286900a600a556127108310610e5657600080fd5b818110610e6257600080fd5b60008111610e6f57600080fd5b60008811610e7c57600080fd5b60008711610e8957600080fd5b600b889055600c879055610ea86b204fce5e3e25026110000000610aae565b600f556009869055610eb985610aae565b600d55610ec584610aae565b600e556010839055806ec097ce7bc90715b34b9f1000000000811515610ee757fe5b04601255816ec097ce7bc90715b34b9f1000000000811515610f0557fe5b04601381905560148390556015829055600b54600c54600954600d54600e54601054600a54600f546012547f52db0a06d138736a4425764a1f7e1b432b5ce79099d523c0c4cd01e7320aba0e998c8c6040519b8c5260208c019a909a526040808c019990995260608b019790975260808a019590955260a089019390935260c088019190915260e0870152610100860152610120850152610140840152610160830191909152610180909101905180910390a15050505050505050565b6000811515610fd357506000610fe7565b8282838502811515610fe157fe5b04141590505b92915050565b600080611003600b54600c548686600a54611324565b600f5490915081111561101557600080fd5b61101e8161107e565b905082670de0b6b3a7640000820281151561103557fe5b04949350505050565b600080600a54670de0b6b3a764000061105f600b54600c5487600a54610ae0565b0281151561106957fe5b0490506110758161107e565b91505b50919050565b600060c860020a82111561109157600080fd5b6010546127109081038302610ad9565b60095481565b60005433600160a060020a039081169116146110c257600080fd5b600160a060020a03811615156110d757600080fd5b6001547f3b81caf78fa51ecbc8acb482fd7012a277b428d9b80f9d156e8a54107496cc4090600160a060020a0316604051600160a060020a03909116815260200160405180910390a160018054600160a060020a031916600160a060020a0392909216919091179055565b60015433600160a060020a0390811691161461115d57600080fd5b6001546000547f65da1cfc2c2e81576ad96afb24a581f8e109b7a403b35cbd3243a1c99efdb9ed91600160a060020a039081169116604051600160a060020a039283168152911660208201526040908101905180910390a16001805460008054600160a060020a0319908116600160a060020a03841617909155169055565b60005433600160a060020a039081169116146111f757600080fd5b600160a060020a038116151561120c57600080fd5b7f3b81caf78fa51ecbc8acb482fd7012a277b428d9b80f9d156e8a54107496cc4081604051600160a060020a03909116815260200160405180910390a16000547f65da1cfc2c2e81576ad96afb24a581f8e109b7a403b35cbd3243a1c99efdb9ed908290600160a060020a0316604051600160a060020a039283168152911660208201526040908101905180910390a160008054600160a060020a031916600160a060020a0392909216919091179055565b6112c6611f34565b6005805480602002602001604051908101604052809291908181526020018280548015610bfa57602002820191906000526020600020908154600160a060020a03168152600190910190602001808311610bdc575050505050905090565b60008060008061133689898988610ae0565b925082890291506113478987610fc2565b1561135157600080fd5b611360868a0286870287611b50565b90508481101561136f57600080fd5b61137b85820386610fc2565b1561138557600080fd5b611393858683030286610fc2565b1561139d57600080fd5b6113ad8586878403020286610fc2565b156113b757600080fd5b6113c18282610fc2565b156113cb57600080fd5b6113d58984610fc2565b156113df57600080fd5b8082028586878885030202028115156113f457fe5b049998505050505050505050565b600080600283810a908102818381881080159061141f5750828811155b151561142a57600080fd5b607d871061143757600080fd5b50855b6000811115611474578388890281151561145057fe5b04975060028204915082881061146b57600288049750938101935b6000190161143a565b50929695505050505050565b6000808283028410156114975750839050826114bd565b6114b883868115156114a557fe5b0484868115156114b157fe5b0485611480565b915091505b935093915050565b6000808080806b204fce5e3e250261100000008711156114e457600080fd5b600f548611156114f357600080fd5b600754600160a060020a038a811691161461151157600094506115c2565b871561155e5761152087610aae565b9350600d5484111561153557600094506115c2565b83151561154c5761154586611dea565b9050611559565b6115568685610fed565b90505b6115b2565b611567876116a2565b92506115728361107e565b915081151561158f576115848661103e565b90506000935061159f565b61159a868484611657565b945090505b600e548411156115b257600094506115c2565b6115bc8189611946565b90508094505b50505050949350505050565b60007f800000000000000000000000000000000000000000000000000000000000000060ff5b6000811261164957838283860281151561160a57fe5b041461161b57600282049150611640565b60008285028681151561162a57fe5b0411156116395780925061164f565b6002820491505b600019016115f4565b60001992505b505092915050565b600080611670600b54600c548786600a546009546117b3565b600f5490915081111561168257600080fd5b83670de0b6b3a7640000820281151561169757fe5b049150935093915050565b60006b204fce5e3e250261100000008211156116bd57600080fd5b6007546116d290600160a060020a0316611e51565b600a0a600a548302811515610ad957fe5b60005433600160a060020a039081169116146116fe57600080fd5b600160a060020a03811660009081526002602052604090205460ff161561172457600080fd5b6004546032901061173457600080fd5b7f091a7a4b85135fdd7e8dbc18b12fabe5cc191ea867aa3c2e1a24a102af61d58b816001604051600160a060020a039092168252151560208201526040908101905180910390a1600160a060020a0381166000908152600260205260409020805460ff191660019081179091556004805490918101610dda8382611f0b565b6000806000806117c58a8a8a89610ae0565b9250828a0291506117d68288610fc2565b156117e057600080fd5b858602868884028115156117f057fe5b048788020111151561180157600080fd5b61181f8688840281151561181157fe5b048788020187880287610b43565b905061182b8a84610fc2565b1561183557600080fd5b61183f8687610fc2565b1561184957600080fd5b6118538288610fc2565b1561185d57600080fd5b6118678187610fc2565b1561187157600080fd5b8986820281151561187e57fe5b049a9950505050505050505050565b60105481565b600080600283900a8180868811156118b2576118af88886115ce565b93505b6118bc8884610fc2565b156118c657600080fd5b6118d08484610fc2565b156118da57600080fd5b6118e8600285900a88610fc2565b156118f257600080fd5b600284900a870288840281151561190557fe5b0491506119128287611402565b905060c860020a848402111561192757600080fd5b60c860020a81111561193857600080fd5b919092020195945050505050565b6000806000831561195e575050601354601254611967565b50506015546014545b8085118061197457508185105b15611982576000925061164f565b69d3c21bcecceda100000085111561199d576000925061164f565b84925061164f565b600854600160a060020a031681565b60006b204fce5e3e250261100000008211156119cf57600080fd5b601054612710036010548302811515610ad957fe5b6000805433600160a060020a03908116911614611a0057600080fd5b600160a060020a03821660009081526002602052604090205460ff161515611a2757600080fd5b50600160a060020a0381166000908152600260205260408120805460ff191690555b600454811015610a115781600160a060020a0316600482815481101515611a6c57fe5b600091825260209091200154600160a060020a03161415611b4857600480546000198101908110611a9957fe5b60009182526020909120015460048054600160a060020a039092169183908110611abf57fe5b60009182526020909120018054600160a060020a031916600160a060020a0392909216919091179055600480546000190190611afb9082611f0b565b507f091a7a4b85135fdd7e8dbc18b12fabe5cc191ea867aa3c2e1a24a102af61d58b826000604051600160a060020a039092168252151560208201526040908101905180910390a1610a11565b600101611a49565b6000806001808083805b611b648489610fc2565b15611b7157819650611c1a565b611b7b8386610fc2565b15611b8857819650611c1a565b848302888502811515611b9757fe5b048201915080821415611bac57819650611c1a565b5060019094019380611bbe848b610fc2565b15611bcb57819650611c1a565b611bd5838a610fc2565b15611be257819650611c1a565b611bec8587610fc2565b15611bf957819650611c1a565b938502939289029291880291611c1084848a611480565b9094509250611b5a565b5050505050509392505050565b6000805433600160a060020a03908116911614611c4357600080fd5b506011805460009091557fdeb4766cf1de6f18e3b195f199d403a02a3e09fbee1192b37d797fb300f052618160405190815260200160405180910390a150565b600080806b204fce5e3e25026110000000841115611ca057600080fd5b600854611cb690600160a060020a031631610aae565b9150611cc4878686856114c5565b905069d3c21bcecceda1000000811115611cdd57600080fd5b9695505050505050565b60085433600160a060020a03908116911614611d0257600080fd5b6000831315611d2a57611d1c611d1784610a91565b6119b4565b601180549091019055611d51565b612710601054611d3985610a91565b02811515611d4357fe5b601180549290910490910190555b50505050565b60005433600160a060020a03908116911614611d7257600080fd5b600160a060020a03811682156108fc0283604051600060405180830381858888f193505050501515611da357600080fd5b7fec47e7ed86c86774d1a72c19f35c639911393fe7c1a34031fdbd260890da90de8282604051918252600160a060020a031660208201526040908101905180910390a15050565b600080611dff600b54600c5485600a54610ae0565b670de0b6b3a7640000600a540281151561106957fe5b60125481565b60155481565b600c5481565b600f5481565b600054600160a060020a031681565b60135481565b600754600160a060020a031681565b600080600160a060020a03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611e825760129150611078565b50600160a060020a038216600090815260066020526040902054801515610fe75782600160a060020a031663313ce5676000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515611ee957600080fd5b6102c65a03f11515611efa57600080fd5b505050604051805190509150611078565b815481835581811511611f2f57600083815260209020611f2f918101908301611f46565b505050565b60206040519081016040526000815290565b610c0291905b80821115611f605760008155600101611f4c565b5090565b600160a060020a03811673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611faa57600160a060020a038116600090815260066020526040902060129055612024565b80600160a060020a031663313ce5676000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515611ff057600080fd5b6102c65a03f1151561200157600080fd5b5050506040518051600160a060020a038316600090815260066020526040902055505b505600a165627a7a7230582061e39ecb3a318e9ec9e62931e1fbf24f56420cfdca616106e0bae5a2a5b796470029
[ 4, 9 ]
0x52a6ddd08efc86892ce3d9074c4b39a571115655
pragma solidity 0.6.8; 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 vaults 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract CryptoPunksMarket { address owner; string public standard = "CryptoPunks"; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public nextPunkIndexToAssign = 0; bool public allPunksAssigned = false; uint256 public punksRemainingToAssign = 0; //mapping (address => uint) public addressToPunkIndex; mapping(uint256 => address) public punkIndexToAddress; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } // A record of punks that are offered for sale at a specific minimum value, and perhaps to a specific person mapping(uint256 => Offer) public punksOfferedForSale; // A record of the highest punk bid mapping(uint256 => Bid) public punkBids; mapping(address => uint256) public pendingWithdrawals; event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public payable { // balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens owner = msg.sender; totalSupply = 10000; // Update total supply punksRemainingToAssign = totalSupply; name = "CRYPTOPUNKS"; // Set the name for display purposes symbol = "Ͼ"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes } function setInitialOwner(address to, uint256 punkIndex) public { // require(msg.sender == owner, "msg.sender != owner"); require(!allPunksAssigned); require(punkIndex < 10000); if (punkIndexToAddress[punkIndex] != to) { if (punkIndexToAddress[punkIndex] != address(0)) { balanceOf[punkIndexToAddress[punkIndex]]--; } else { punksRemainingToAssign--; } punkIndexToAddress[punkIndex] = to; balanceOf[to]++; emit PunkTransfer(address(0), to, punkIndex); } } function setInitialOwners( address[] memory addresses, uint256[] memory indices ) public { require(msg.sender == owner); uint256 n = addresses.length; for (uint256 i = 0; i < n; i++) { setInitialOwner(addresses[i], indices[i]); } } function allInitialOwnersAssigned() public { require(msg.sender == owner); allPunksAssigned = true; } function getPunk(uint256 punkIndex) public { // require(allPunksAssigned); require(punksRemainingToAssign != 0); require(punkIndexToAddress[punkIndex] == address(0)); require(punkIndex < 10000); punkIndexToAddress[punkIndex] = msg.sender; balanceOf[msg.sender]++; punksRemainingToAssign--; emit Assign(msg.sender, punkIndex); } // Transfer ownership of a punk to another user without requiring payment function transferPunk(address to, uint256 punkIndex) public { // // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); if (punksOfferedForSale[punkIndex].isForSale) { punkNoLongerForSale(punkIndex); } punkIndexToAddress[punkIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; emit Transfer(msg.sender, to, 1); emit PunkTransfer(msg.sender, to, punkIndex); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == to) { // Kill bid and revault value pendingWithdrawals[to] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function punkNoLongerForSale(uint256 punkIndex) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, msg.sender, 0, address(0) ); emit PunkNoLongerForSale(punkIndex); } function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, address(0) ); emit PunkOffered(punkIndex, minSalePriceInWei, address(0)); } function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, toAddress ); emit PunkOffered(punkIndex, minSalePriceInWei, toAddress); } function buyPunk(uint256 punkIndex) public payable { // require(allPunksAssigned); Offer storage offer = punksOfferedForSale[punkIndex]; require(punkIndex < 10000); require(offer.isForSale); // punk not actually for sale (offer.onlySellTo == address(0) || offer.onlySellTo == msg.sender); // punk not supposed to be sold to this user require(msg.value >= offer.minValue); // Didn't send enough ETH require(offer.seller == punkIndexToAddress[punkIndex]); // Seller no longer owner of punk address seller = offer.seller; punkIndexToAddress[punkIndex] = msg.sender; balanceOf[seller]--; balanceOf[msg.sender]++; emit Transfer(seller, msg.sender, 1); punkNoLongerForSale(punkIndex); pendingWithdrawals[seller] += msg.value; emit PunkBought(punkIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == msg.sender) { // Kill bid and revault value pendingWithdrawals[msg.sender] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function withdraw() public { // require(allPunksAssigned); uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending revault before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } function enterBidForPunk(uint256 punkIndex) public payable { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); require(msg.value != 0); Bid storage existing = punkBids[punkIndex]; require(msg.value > existing.value); if (existing.value > 0) { // Revault the failing bid pendingWithdrawals[existing.bidder] += existing.value; } punkBids[punkIndex] = Bid(true, punkIndex, msg.sender, msg.value); emit PunkBidEntered(punkIndex, msg.value, msg.sender); } function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); address seller = msg.sender; Bid storage bid = punkBids[punkIndex]; require(bid.value != 0); require(bid.value >= minPrice); punkIndexToAddress[punkIndex] = bid.bidder; balanceOf[seller]--; balanceOf[bid.bidder]++; emit Transfer(seller, bid.bidder, 1); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, bid.bidder, 0, address(0) ); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); pendingWithdrawals[seller] += amount; emit PunkBought(punkIndex, bid.value, seller, bid.bidder); } function withdrawBidForPunk(uint256 punkIndex) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); Bid storage bid = punkBids[punkIndex]; require(bid.bidder == msg.sender); emit PunkBidWithdrawn(punkIndex, bid.value, msg.sender); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); // Revault the bid money msg.sender.transfer(amount); } } 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)); } } interface ICryptoPunksMarket { struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; address onlySellTo; } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); function setInitialOwner(address to, uint256 punkIndex) external; function setInitialOwners( address[] calldata addresses, uint256[] calldata indices ) external; function allInitialOwnersAssigned() external; function getPunk(uint256 punkIndex) external; function transferPunk(address to, uint256 punkIndex) external; function punkNoLongerForSale(uint256 punkIndex) external; function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) external; function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) external; function buyPunk(uint256 punkIndex) external; function withdraw() external; function enterBidForPunk(uint256 punkIndex) external; function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) external; function withdrawBidForPunk(uint256 punkIndex) external; function punkIndexToAddress(uint256 punkIndex) external returns (address); function punksOfferedForSale(uint256 punkIndex) external returns ( bool isForSale, uint256 _punkIndex, address seller, uint256 minValue, address onlySellTo ); function balanceOf(address user) external returns (uint256); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IXToken is IERC20 { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function mint(address to, uint256 amount) external; function changeName(string calldata name) external; function changeSymbol(string calldata symbol) external; function setVaultAddress(address vaultAddress) external; } 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; } } contract Pausable is Ownable { bool private isPaused = false; event Paused(); event Unpaused(); function getIsPaused() public view returns (bool) { return isPaused; } function pause() public onlyOwner { isPaused = true; } function unpause() public onlyOwner { isPaused = false; } modifier whenPaused { require(isPaused, "Contract is not paused"); _; } modifier whenNotPaused { require(!isPaused, "Contract is paused"); _; } } 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 revault on every call to nonReentrant will be lower in // amount. Since revaults 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 revault 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 revault is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract XVaultBase is Pausable { address private erc20Address; address private cpmAddress; IXToken private erc20; ICryptoPunksMarket private cpm; function getERC20Address() public view returns (address) { return erc20Address; } function getCpmAddress() public view returns (address) { return cpmAddress; } function getERC20() internal view returns (IXToken) { return erc20; } function getCPM() internal view returns (ICryptoPunksMarket) { return cpm; } function setERC20Address(address newAddress) internal { require(erc20Address == address(0), "Already initialized ERC20"); erc20Address = newAddress; erc20 = IXToken(erc20Address); } function setCpmAddress(address newAddress) internal { require(cpmAddress == address(0), "Already initialized CPM"); cpmAddress = newAddress; cpm = ICryptoPunksMarket(cpmAddress); } } contract XVaultSafe is XVaultBase, ReentrancyGuard { using EnumerableSet for EnumerableSet.UintSet; EnumerableSet.UintSet private reserves; bool private inSafeMode = true; event TokenBurnedSafely(uint256 punkId, address indexed to); function getReserves() internal view returns (EnumerableSet.UintSet storage) { return reserves; } function getInSafeMode() public view returns (bool) { return inSafeMode; } function turnOffSafeMode() public onlyOwner { inSafeMode = false; } function turnOnSafeMode() public onlyOwner { inSafeMode = true; } modifier whenNotInSafeMode { require(!inSafeMode, "Contract is in safe mode"); _; } function simpleRedeem() public whenPaused nonReentrant { require( getERC20().balanceOf(msg.sender) >= 10**18, "ERC20 balance too small" ); require( getERC20().allowance(msg.sender, address(this)) >= 10**18, "ERC20 allowance too small" ); uint256 tokenId = reserves.at(0); getERC20().burnFrom(msg.sender, 10**18); reserves.remove(tokenId); getCPM().transferPunk(msg.sender, tokenId); emit TokenBurnedSafely(tokenId, msg.sender); } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _changeName(string memory name_) internal { _name = name_; } function _changeSymbol(string memory symbol_) internal { _symbol = symbol_; } /** * @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 {} } abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } contract Timelocked is XVaultSafe { using SafeMath for uint256; enum Timelock {Short, Medium, Long} uint256 private securityLevel; function getSecurityLevel() public view returns (string memory) { if (securityLevel == 0) { return "red"; } else if (securityLevel == 1) { return "orange"; } else if (securityLevel == 2) { return "yellow"; } else { return "green"; } } function increaseSecurityLevel() public onlyOwner { require(securityLevel < 3, "Already max"); securityLevel = securityLevel + 1; } function timeInDays(uint256 num) internal pure returns (uint256) { return num * 60 * 60 * 24; } function getDelay(Timelock lockId) public view returns (uint256) { if (securityLevel == 0) { return 2; // for testing } if (lockId == Timelock.Short) { if (securityLevel == 1) { return timeInDays(1); } else if (securityLevel == 2) { return timeInDays(2); } else { return timeInDays(3); } } else if (lockId == Timelock.Medium) { if (securityLevel == 1) { return timeInDays(2); } else if (securityLevel == 2) { return timeInDays(3); } else { return timeInDays(5); } } else { if (securityLevel == 1) { return timeInDays(3); } else if (securityLevel == 2) { return timeInDays(5); } else { return timeInDays(10); } } } mapping(Timelock => uint256) private releaseTimes; event Locked(Timelock lockId); event UnlockInitiated(Timelock lockId, uint256 whenUnlocked); function getReleaseTime(Timelock lockId) public view returns (uint256) { return releaseTimes[lockId]; } function initiateUnlock(Timelock lockId) public onlyOwner { uint256 newReleaseTime = now.add(getDelay(lockId)); releaseTimes[lockId] = newReleaseTime; emit UnlockInitiated(lockId, newReleaseTime); } function lock(Timelock lockId) public onlyOwner { releaseTimes[lockId] = 0; emit Locked(lockId); } modifier whenNotLockedS { uint256 releaseTime = releaseTimes[Timelock.Short]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedM { uint256 releaseTime = releaseTimes[Timelock.Medium]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedL { uint256 releaseTime = releaseTimes[Timelock.Long]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } } contract XToken is Context, Ownable, ERC20Burnable { address private vaultAddress; constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _mint(msg.sender, 0); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function changeName(string memory name) public onlyOwner { _changeName(name); } function changeSymbol(string memory symbol) public onlyOwner { _changeSymbol(symbol); } function getVaultAddress() public view returns (address) { return vaultAddress; } function setVaultAddress(address newAddress) public onlyOwner { vaultAddress = newAddress; } } contract Profitable is Timelocked { mapping(address => bool) private verifiedIntegrators; uint256 private numIntegrators = 0; uint256[] private mintFees = [0, 0, 0]; uint256[] private burnFees = [0, 0, 0, (5 * 10**18), 20]; uint256[] private dualFees = [0, 0, 0]; event MintFeesSet(uint256[] mintFees); event BurnFeesSet(uint256[] burnFees); event DualFeesSet(uint256[] dualFees); event IntegratorSet(address account, bool isVerified); event Withdrawal(address to, uint256 amount); function getMintFees() public view returns (uint256[] memory) { return mintFees; } function getBurnFees() public view returns (uint256[] memory) { return burnFees; } function getDualFees() public view returns (uint256[] memory) { return dualFees; } function _getMintFees() internal view returns (uint256[] storage) { return mintFees; } function _getBurnFees() internal view returns (uint256[] storage) { return burnFees; } function _getDualFees() internal view returns (uint256[] storage) { return dualFees; } function setMintFees(uint256[] memory newMintFees) public onlyOwner whenNotLockedM { require(newMintFees.length == 3, "Wrong length"); mintFees = newMintFees; emit MintFeesSet(newMintFees); } function setBurnFees(uint256[] memory newBurnFees) public onlyOwner whenNotLockedL { require(newBurnFees.length == 5, "Wrong length"); burnFees = newBurnFees; emit BurnFeesSet(newBurnFees); } function setDualFees(uint256[] memory newDualFees) public onlyOwner whenNotLockedM { require(newDualFees.length == 3, "Wrong length"); dualFees = newDualFees; emit DualFeesSet(newDualFees); } function isIntegrator(address account) public view returns (bool) { return verifiedIntegrators[account]; } function getNumIntegrators() public view returns (uint256) { return numIntegrators; } function setIntegrator(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedIntegrators[account], "Already set"); if (isVerified) { numIntegrators = numIntegrators.add(1); } else { numIntegrators = numIntegrators.sub(1); } verifiedIntegrators[account] = isVerified; emit IntegratorSet(account, isVerified); } function getFee(address account, uint256 numTokens, uint256[] storage fees) internal view returns (uint256) { uint256 fee = 0; if (verifiedIntegrators[account]) { return 0; } else if (numTokens == 1) { fee = fees[0]; } else { fee = fees[1] + numTokens * fees[2]; } // if this is a burn operation... if (fees.length > 3) { // if reserves are low... uint256 reservesLength = getReserves().length(); uint256 padding = fees[4]; if (reservesLength - numTokens <= padding) { uint256 addedFee = 0; for (uint256 i = 0; i < numTokens; i++) { if ( reservesLength - i <= padding && reservesLength - i > 0 ) { addedFee += (fees[3] * (padding - (reservesLength - i) + 1)); } } fee += addedFee; } } return fee; } function withdraw(address payable to) public onlyOwner whenNotLockedM { uint256 balance = address(this).balance; to.transfer(balance); emit Withdrawal(to, balance); } } contract Controllable is Profitable { mapping(address => bool) private verifiedControllers; uint256 private numControllers = 0; event ControllerSet(address account, bool isVerified); event DirectRedemption(uint256 punkId, address by, address indexed to); function isController(address account) public view returns (bool) { return verifiedControllers[account]; } function getNumControllers() public view returns (uint256) { return numControllers; } function setController(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedControllers[account], "Already set"); if (isVerified) { numControllers++; } else { numControllers--; } verifiedControllers[account] = isVerified; emit ControllerSet(account, isVerified); } modifier onlyController() { require(isController(_msgSender()), "Not a controller"); _; } function directRedeem(uint256 tokenId, address to) public onlyController { require(getERC20().balanceOf(to) >= 10**18, "ERC20 balance too small"); bool toSelf = (to == address(this)); require( toSelf || (getERC20().allowance(to, address(this)) >= 10**18), "ERC20 allowance too small" ); require(getReserves().contains(tokenId), "Not in holdings"); getERC20().burnFrom(to, 10**18); getReserves().remove(tokenId); if (!toSelf) { getCPM().transferPunk(to, tokenId); } emit DirectRedemption(tokenId, _msgSender(), to); } } contract Randomizable is Controllable { uint256 private randNonce = 0; function getPseudoRand(uint256 modulus) internal returns (uint256) { randNonce = randNonce.add(1); return uint256(keccak256(abi.encodePacked(now, _msgSender(), randNonce))) % modulus; } } contract Manageable is Randomizable { event MigrationComplete(address to); event TokenNameChange(string name); event TokenSymbolChange(string symbol); function migrate(address to) public onlyOwner whenNotLockedL { uint256 reservesLength = getReserves().length(); for (uint256 i = 0; i < reservesLength; i++) { uint256 tokenId = getReserves().at(i); getCPM().transferPunk(to, tokenId); } emit MigrationComplete(to); } function changeTokenName(string memory newName) public onlyOwner whenNotLockedM { getERC20().changeName(newName); emit TokenNameChange(newName); } function changeTokenSymbol(string memory newSymbol) public onlyOwner whenNotLockedM { getERC20().changeSymbol(newSymbol); emit TokenSymbolChange(newSymbol); } function setReverseLink() public onlyOwner whenNotLockedS { getERC20().setVaultAddress(address(this)); } } contract XVault is Manageable { event TokenMinted(uint256 tokenId, address indexed to); event TokensMinted(uint256[] tokenIds, address indexed to); event TokenBurned(uint256 tokenId, address indexed to); event TokensBurned(uint256[] tokenIds, address indexed to); constructor(address erc20Address, address cpmAddress) public { setERC20Address(erc20Address); setCpmAddress(cpmAddress); } function getCryptoPunkAtIndex(uint256 index) public view returns (uint256) { return getReserves().at(index); } function getReservesLength() public view returns (uint256) { return getReserves().length(); } function isCryptoPunkDeposited(uint256 tokenId) public view returns (bool) { return getReserves().contains(tokenId); } function mintPunk(uint256 tokenId) public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getMintFees()); require(msg.value >= fee, "Value too low"); _mintPunk(tokenId, false); } function _mintPunk(uint256 tokenId, bool partOfDualOp) private returns (bool) { address msgSender = _msgSender(); require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); require(_tokenId == tokenId, "Wrong punk"); require(forSale, "Punk not available"); require(buyer == address(this), "Transfer not approved"); require(minVal == 0, "Min value not zero"); require(msgSender == seller, "Sender is not seller"); require( msgSender == getCPM().punkIndexToAddress(tokenId), "Sender is not owner" ); getCPM().buyPunk(tokenId); getReserves().add(tokenId); if (!partOfDualOp) { uint256 tokenAmount = 10**18; getERC20().mint(msgSender, tokenAmount); } emit TokenMinted(tokenId, _msgSender()); return true; } function mintPunkMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), tokenIds.length, _getMintFees()); require(msg.value >= fee, "Value too low"); _mintPunkMultiple(tokenIds, false); } function _mintPunkMultiple(uint256[] memory tokenIds, bool partOfDualOp) private returns (uint256) { require(tokenIds.length > 0, "No tokens"); require(tokenIds.length <= 100, "Over 100 tokens"); uint256[] memory newTokenIds = new uint256[](tokenIds.length); uint256 numNewTokens = 0; address msgSender = _msgSender(); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); bool rightToken = _tokenId == tokenId; bool isApproved = buyer == address(this); bool priceIsZero = minVal == 0; bool isSeller = msgSender == seller; bool isOwner = msgSender == getCPM().punkIndexToAddress(tokenId); if ( forSale && rightToken && isApproved && priceIsZero && isSeller && isOwner ) { getCPM().buyPunk(tokenId); getReserves().add(tokenId); newTokenIds[numNewTokens] = tokenId; numNewTokens = numNewTokens.add(1); } } if (numNewTokens > 0) { if (!partOfDualOp) { uint256 tokenAmount = numNewTokens * (10**18); getERC20().mint(msgSender, tokenAmount); } emit TokensMinted(newTokenIds, msgSender); } return numNewTokens; } function redeemPunk() public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getBurnFees()); require(msg.value >= fee, "Value too low"); _redeemPunk(false); } function _redeemPunk(bool partOfDualOp) private { address msgSender = _msgSender(); uint256 tokenAmount = 10**18; require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); emit TokenBurned(tokenId, msgSender); } function redeemPunkMultiple(uint256 numTokens) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), numTokens, _getBurnFees()); require(msg.value >= fee, "Value too low"); _redeemPunkMultiple(numTokens, false); } function _redeemPunkMultiple(uint256 numTokens, bool partOfDualOp) private { require(numTokens > 0, "No tokens"); require(numTokens <= 100, "Over 100 tokens"); address msgSender = _msgSender(); uint256 tokenAmount = numTokens * (10**18); require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } uint256[] memory tokenIds = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); tokenIds[i] = tokenId; getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); } emit TokensBurned(tokenIds, msgSender); } function mintAndRedeem(uint256 tokenId) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), 1, _getDualFees()); require(msg.value >= fee, "Value too low"); require(_mintPunk(tokenId, true), "Minting failed"); _redeemPunk(true); } function mintAndRedeemMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 numTokens = tokenIds.length; require(numTokens > 0, "No tokens"); require(numTokens <= 20, "Over 20 tokens"); uint256 fee = getFee(_msgSender(), numTokens, _getDualFees()); require(msg.value >= fee, "Value too low"); uint256 numTokensMinted = _mintPunkMultiple(tokenIds, true); if (numTokensMinted > 0) { _redeemPunkMultiple(numTokens, true); } } function mintRetroactively(uint256 tokenId, address to) public onlyOwner whenNotLockedS { require( getCPM().punkIndexToAddress(tokenId) == address(this), "Not owner" ); require(!getReserves().contains(tokenId), "Already in reserves"); uint256 cryptoPunkBalance = getCPM().balanceOf(address(this)); require( (getERC20().totalSupply() / (10**18)) < cryptoPunkBalance, "No excess NFTs" ); getReserves().add(tokenId); getERC20().mint(to, 10**18); emit TokenMinted(tokenId, _msgSender()); } function redeemRetroactively(address to) public onlyOwner whenNotLockedS { require( getERC20().balanceOf(address(this)) >= (10**18), "Not enough PUNK" ); getERC20().burn(10**18); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); getReserves().remove(tokenId); getCPM().transferPunk(to, tokenId); emit TokenBurned(tokenId, _msgSender()); } }
0x608060405234801561001057600080fd5b50600436106101375760003560e01c806370a08231116100b857806395d89b411161007c57806395d89b4114610430578063a3895fff14610438578063a457c2d7146104de578063a9059cbb1461050a578063dd62ed3e14610536578063f2fde38b1461056457610137565b806370a08231146103a8578063715018a6146103ce57806379cc6790146103d657806385535cc5146104025780638da5cb5b1461042857610137565b806339509351116100ff578063395093511461026757806340c10f191461029357806342966c68146102c15780635353a2d8146102de57806365cacaa41461038457610137565b806306fdde031461013c578063095ea7b3146101b957806318160ddd146101f957806323b872dd14610213578063313ce56714610249575b600080fd5b61014461058a565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561017e578181015183820152602001610166565b50505050905090810190601f1680156101ab5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101e5600480360360408110156101cf57600080fd5b506001600160a01b038135169060200135610621565b604080519115158252519081900360200190f35b61020161063e565b60408051918252519081900360200190f35b6101e56004803603606081101561022957600080fd5b506001600160a01b03813581169160208101359091169060400135610644565b6102516106d1565b6040805160ff9092168252519081900360200190f35b6101e56004803603604081101561027d57600080fd5b506001600160a01b0381351690602001356106da565b6102bf600480360360408110156102a957600080fd5b506001600160a01b03813516906020013561072e565b005b6102bf600480360360208110156102d757600080fd5b5035610794565b6102bf600480360360208110156102f457600080fd5b81019060208101813564010000000081111561030f57600080fd5b82018360208201111561032157600080fd5b8035906020019184600183028401116401000000008311171561034357600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295506107a8945050505050565b61038c610809565b604080516001600160a01b039092168252519081900360200190f35b610201600480360360208110156103be57600080fd5b50356001600160a01b031661081d565b6102bf610838565b6102bf600480360360408110156103ec57600080fd5b506001600160a01b0381351690602001356108da565b6102bf6004803603602081101561041857600080fd5b50356001600160a01b031661093a565b61038c6109ba565b6101446109c9565b6102bf6004803603602081101561044e57600080fd5b81019060208101813564010000000081111561046957600080fd5b82018360208201111561047b57600080fd5b8035906020019184600183028401116401000000008311171561049d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610a2a945050505050565b6101e5600480360360408110156104f457600080fd5b506001600160a01b038135169060200135610a8b565b6101e56004803603604081101561052057600080fd5b506001600160a01b038135169060200135610af9565b6102016004803603604081101561054c57600080fd5b506001600160a01b0381358116916020013516610b0d565b6102bf6004803603602081101561057a57600080fd5b50356001600160a01b0316610b38565b60048054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156106165780601f106105eb57610100808354040283529160200191610616565b820191906000526020600020905b8154815290600101906020018083116105f957829003601f168201915b505050505090505b90565b600061063561062e610c91565b8484610c95565b50600192915050565b60035490565b6000610651848484610d81565b6106c78461065d610c91565b6106c28560405180606001604052806028815260200161133b602891396001600160a01b038a1660009081526002602052604081209061069b610c91565b6001600160a01b03168152602081019190915260400160002054919063ffffffff610eea16565b610c95565b5060019392505050565b60065460ff1690565b60006106356106e7610c91565b846106c285600260006106f8610c91565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff610c3016565b610736610c91565b6000546001600160a01b03908116911614610786576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107908282610f81565b5050565b6107a561079f610c91565b8261107f565b50565b6107b0610c91565b6000546001600160a01b03908116911614610800576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107a581611187565b60065461010090046001600160a01b031690565b6001600160a01b031660009081526001602052604090205490565b610840610c91565b6000546001600160a01b03908116911614610890576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000610917826040518060600160405280602481526020016113836024913961090a86610905610c91565b610b0d565b919063ffffffff610eea16565b905061092b83610925610c91565b83610c95565b610935838361107f565b505050565b610942610c91565b6000546001600160a01b03908116911614610992576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b600680546001600160a01b0390921661010002610100600160a81b0319909216919091179055565b6000546001600160a01b031690565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156106165780601f106105eb57610100808354040283529160200191610616565b610a32610c91565b6000546001600160a01b03908116911614610a82576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6107a58161119a565b6000610635610a98610c91565b846106c2856040518060600160405280602581526020016114116025913960026000610ac2610c91565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff610eea16565b6000610635610b06610c91565b8484610d81565b6001600160a01b03918216600090815260026020908152604080832093909416825291909152205490565b610b40610c91565b6000546001600160a01b03908116911614610b90576040805162461bcd60e51b81526020600482018190526024820152600080516020611363833981519152604482015290519081900360640190fd5b6001600160a01b038116610bd55760405162461bcd60e51b81526004018080602001828103825260268152602001806112cd6026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b600082820183811015610c8a576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b3390565b6001600160a01b038316610cda5760405162461bcd60e51b81526004018080602001828103825260248152602001806113ed6024913960400191505060405180910390fd5b6001600160a01b038216610d1f5760405162461bcd60e51b81526004018080602001828103825260228152602001806112f36022913960400191505060405180910390fd5b6001600160a01b03808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b038316610dc65760405162461bcd60e51b81526004018080602001828103825260258152602001806113c86025913960400191505060405180910390fd5b6001600160a01b038216610e0b5760405162461bcd60e51b81526004018080602001828103825260238152602001806112886023913960400191505060405180910390fd5b610e16838383610935565b610e5981604051806060016040528060268152602001611315602691396001600160a01b038616600090815260016020526040902054919063ffffffff610eea16565b6001600160a01b038085166000908152600160205260408082209390935590841681522054610e8e908263ffffffff610c3016565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610f795760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610f3e578181015183820152602001610f26565b50505050905090810190601f168015610f6b5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6001600160a01b038216610fdc576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b610fe860008383610935565b600354610ffb908263ffffffff610c3016565b6003556001600160a01b038216600090815260016020526040902054611027908263ffffffff610c3016565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6001600160a01b0382166110c45760405162461bcd60e51b81526004018080602001828103825260218152602001806113a76021913960400191505060405180910390fd5b6110d082600083610935565b611113816040518060600160405280602281526020016112ab602291396001600160a01b038516600090815260016020526040902054919063ffffffff610eea16565b6001600160a01b03831660009081526001602052604090205560035461113f908263ffffffff6111ad16565b6003556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b80516107909060049060208401906111ef565b80516107909060059060208401906111ef565b6000610c8a83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610eea565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061123057805160ff191683800117855561125d565b8280016001018555821561125d579182015b8281111561125d578251825591602001919060010190611242565b5061126992915061126d565b5090565b61061e91905b80821115611269576000815560010161127356fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a206275726e20616d6f756e7420657863656564732062616c616e63654f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e63654f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657245524332303a206275726e20616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa26469706673582212200a9307e6f3bc40fafe5096864137b5035439b04e81ed986f67ce209fccb21f0964736f6c63430006080033
[ 10, 5 ]
0x52d70788b6bf2729060e11cb4c576feb9abda51a
pragma solidity 0.6.12; kenAddress, string TokenName, string TokenSymbol, uint Decimals ); function updateEcoceliumAddress(address ecoAddress) public { require(msg.sender == owner); EcoceliumAddress = ecoAddress; f rivate 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; } 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; } } 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 rol ing `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 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()); } } } contract ERC20Basic { uint public _totalSupply; string public name; string public symbol; uint public decimals; function totalSupply() public view returns (uint){} function balanceOf(address who) public view returns (uint){} function transfer(address to, uint value) public {} function transferFrom(address _from, address _to, uint _value) public{} function allowance(address _owner, address _spender) public view returns (uint remaining) {} event Transfer(address indexed from, address indexed to, uint value); } 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`. */ f alanceOf(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. * alue changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => uint256) public lockedAmount; 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,uint8 decimals) publi _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. 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 availableAmount(address owner) public view returns(uint256){ return balanceOf(owner).sub(lockedAmount[owner]); } 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"); require(amount <= availableAmount(sender),"ERC20 : amount exceeds available amount"); _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"); require(amount <= availableAmount(account),"ERC20 : burn exceeds available amount"); _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"); require(amount <= availableAmount(owner),"ERC20 : approve amount exceeds available amount"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _lock(address owner,uint256 amount) internal virtual { require(owner != address(0), "ERC20: lock for zero address"); require(amount <= availableAmount(owner),"ERC20: lock value more tha available amount"); lockedAmount[owner] = lockedAmount[owner].add(amount); } function _release(address owner,uint256 amount) internal virtual{ require(owner != address(0), "ERC20: release for zero address"); require(amount <= lockedAmount[owner],"ERC20 : release value more then locked value"); lockedAmount[owner] = lockedAmount[owner].sub(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 { } } 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 0xc5d2460186f7233c927e7db2dcc703c0e500b 3b7bfad8045d85a470 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); } } } } 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 th as 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)); } } 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 su SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ m henNotPaused() { 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()); } } 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"); } } contract wERC20 is Context, AccessControl, ERC20, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant ETMOWNER_ROLE = keccak256("ETM_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the t that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol,uint8 decimals,address admin,address etmOwner) public ERC20(name, symbol,decimals) { _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(ETMOWNER_ROLE, etmOwner); _setupRole(MINTER_ROLE, admin); _setupRole(PAUSER_ROLE, admin); } /** * @dev Creates `amount` s 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); } function burnFrom(address _from,uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to burn"); _burn(_from,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(); } function changeAdmin(address admin) public virtual{ require(hasRole(ETMOWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role"); _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(MINTER_ROLE, admin); _setupRole(PAUSER_ROLE, admin); } /** * @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 lock(address account , uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to lock"); _lock(account,amount); } function release(address account , uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to release"); _release(account,amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } ddress => BorrowatOrder) borrows; string token; Status status; } struct BorrowatOrder{ uint64 orderId; uint amount; uint duration; uint dated; uint duesPaid; } struct freeStorage{ uint amount; uint time; string wtoken; uint usdvalue; } struct User{ uint ecoWithdrawls; uint totalDeposit; uint totalBorrowed; freeStorage [] myDeposits; freeStorage [] myBorrows; mapping(string => uint) deposits; mapping(string => uint) borrows; uint64 [] borrowedOrders; uint64 [] createdOrders; mapping(string => uint) tokenYield; } function initializeAddress(address ETMaddress,address AbacusAddress, address ES1address) external { ETM = EcoceliumTokenManager(ETMaddress); abacus = IAbacusOracle(AbacusAddress); ES1 = EcoceliumSub1(ES1address); } /*============Main Functions=============== ---------------------------------*/ function zeroDepositorPush(address userAddress, string memory _tokenSymbol, uint _amount) external { if(ES1.friendlyaddress(msg.sender)){ uint tokenUsdValue = _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].totalDeposit += tokenUsdValue; freeStorage memory newDeposit = freeStorage({ amount: _amount, time: now, wtoken: _tokenSymbol, usdvalue: tokenUsdValue }); users[userAddress].myDeposits.push(newDeposit); users[userAddress].deposits[_tokenSymbol] += _amount; } } /*function getUsersOrders(address userAddress) public view returns(uint64 [] memory){ return users[userAddress].createdOrders; }*/ function getUserDepositsbyToken(address userAddress, string memory wtoken) public view returns(uint) { return users[userAddress].deposits[wtoken]; } function getbuyPower(address userAddress) public view returns (uint){ uint buyPower; if(!ES1.isRegistrar(userAddress)) { if(ES1.isUserLocked(userAddress)) { return 0; } buyPower += users[userAddress].totalDeposit - ((users[userAddress].totalDeposit*ES1.CDSpercent())/100); buyPower -= users[userAddress].totalBorrowed; } else { buyPower = (10**20); } return buyPower; } function createOrder(address userAddress,string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield,address _contractAddress) external{ //_order(userAddress,_tokenSymbol,_amount,_duration,_yield,_contractAddress); if(ES1.friendlyaddress(msg.sender)){ wERC20 token = wERC20(ETM.getwTokenAddress(_tokenSymbol)); // uint amount = _amount*(10**uint(token.decimals())); require(token.availableAmount(userAddress)>= (_amount*(10**uint(token.decimals()))),"insufficient balance"); (uint64 _orderId,uint newAmount,uint fee) = _ordersub(_amount*(10**uint(token.decimals())),userAddress,_duration,_tokenSymbol); address [] memory _borrowers; Orders[_orderId] = Order({ creator : userAddress, borrowers : _borrowers, time : now, duration : _duration, amount : newAmount, amountLeft : newAmount, token : _tokenSymbol, yield : _yield, earnings : 0, status : Status.OPEN, expiryDate : now + _duration*(30 days) }); token.burnFrom(userAddress,fee); token.lock(userAddress,newAmount); ES1.setOwnerFeeVault(_tokenSymbol, fee); orderIds.push(_orderId); users[userAddress].totalDeposit += _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].createdOrders.push(_orderId); scheduleExpiry(_orderId, _contractAddress); ES1.emitOrderCreated(userAddress,_duration,_yield,newAmount,_tokenSymbol); } } function _ordersub(uint amount,address userAddress,uint _duration,string memory _tokenSymbol) internal view returns (uint64, uint, uint){ uint newAmount = amount - (amount*ES1.tradeFee())/100; uint fee = (amount*ES1.tradeFee())/100; uint64 _orderId = uint64(uint(keccak256(abi.encodePacked(userAddress,_tokenSymbol,_duration,now)))); return (_orderId,newAmount,fee); } /*function getTokenByOrderID(uint64 _orderId) public view returns (uint, string memory) { return (Orders[_orderId].earnings,Orders[_orderId].token); }*/ function borrow(uint64 _orderId,uint _amount,uint _duration,address msgSender,address _contractAddress) external { if((ES1.friendlyaddress(msg.sender)) && Orders[_orderId].creator != address(0)) { if((Orders[_orderId].expiryDate - now > _duration*(30 days) && _duration>0 && _duration%1 == 0 && Orders[_orderId].status == Status.OPEN)){ uint usdValue = _amount*fetchTokenPrice(Orders[_orderId].token)/(10**8); if((getbuyPower(msgSender) >= usdValue && Orders[_orderId].amountLeft >= _amount)){ wERC20 token = wERC20(ETM.getwTokenAddress(Orders[_orderId].token)); uint amount = _amount*(10**uint(token.decimals())); token.release(Orders[_orderId].creator,amount); token.burnFrom(Orders[_orderId].creator,amount); token.mint(msgSender,_amount); Orders[_orderId].amountLeft -= _amount; users[msgSender].borrowedOrders.push(_orderId); users[msgSender].totalBorrowed += usdValue; Orders[_orderId].borrowers.push(msgSender); Orders[_orderId].borrows[msgSender] = BorrowatOrder({ orderId : _orderId, amount : _amount, duration : _duration, dated : now, duesPaid : 0 }); scheduleCheck(_orderId,msgSender,1,_contractAddress); if(Orders[_orderId].amountLeft == 0){ Orders[_orderId].status = Status.CLOSED; } ES1.emitBorrowed(_orderId,msgSender,_amount,_duration); } } } } function payDue(uint64 _orderId,uint _duration,address msgSender) public{ if((ES1.friendlyaddress(msg.sender) && (Orders[_orderId].borrows[msgSender].duesPaid <= Orders[_orderId].borrows[msgSender].duration ))){ wERC20 ecoToken = wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())); uint due = orderMonthlyDue(_orderId,msgSender,_duration)*(10**uint(ecoToken.decimals())); uint fee = (due*ES1.rewardFee())/100; ecoToken.burnFrom(msgSender,due); ES1.setOwnerFeeVault(ES1.WRAP_ECO_SYMBOL(), fee); ecoToken.mint(Orders[_orderId].creator,due-fee); users[Orders[_orderId].creator].tokenYield[Orders[_orderId].token] += due - fee; Orders[_orderId].borrows[msgSender].duesPaid += 1; Orders[_orderId].earnings += due - fee; YieldForTokens[Orders[_orderId].token] += due; if(Orders[_orderId].borrows[msgSender].duesPaid == Orders[_orderId].borrows[msgSender].duration) { ES1.setUserLocked(msgSender,false); } ES1.emitDuePaid(_orderId,msgSender,orderMonthlyDue(_orderId,msgSender,_duration)); } } function orderExpired(uint64 _orderId) external { if(ES1.friendlyaddress(msg.sender) && (Orders[_orderId].expiryDate <= now)){ wERC20(ETM.getwTokenAddress(Orders[_orderId].token)).release(Orders[_orderId].creator,Orders[_orderId].amountLeft); users[Orders[_orderId].creator].totalDeposit -= Orders[_orderId].amount*fetchTokenPrice(Orders[_orderId].token)/(10**8); Orders[_orderId].status = Status.CLOSED; } } function scheduleExpiry(uint64 _orderId,address _contractAddress) internal{ uint time = Orders[_orderId].expiryDate - Orders[_orderId].time; bytes memory data = abi.encodeWithSelector(bytes4(keccak256('orderExpired(uint256)')),_orderId); uint callCost = 300000*1e9 + abacus.callFee(); abacus.scheduleFunc{value:callCost}(_contractAddress, time ,data , abacus.callFee() ,300000 , 1e9 ); } function scheduleCheck(uint _orderId,address borrower,uint month,address _contractAddress) internal{ bytes memory data = abi.encodeWithSelector(bytes4(keccak256('dueCheck(uint256,address,uint256)')),_orderId,borrower,month, _contractAddress); uint callCost = 300000*1e9 + abacus.callFee(); abacus.scheduleFunc{value:callCost}(_contractAddress, 30 days ,data , abacus.callFee() ,300000 , 1e9 ); } function cancelOrder(uint64 _orderId) external{ if(ES1.friendlyaddress(msg.sender) && Orders[_orderId].amount == Orders[_orderId].amountLeft){ wERC20(ETM.getwTokenAddress(Orders[_orderId].token)).release(Orders[_orderId].creator,Orders[_orderId].amountLeft); Orders[_orderId].status = Status.CLOSED; } } function dueCheck(uint64 _orderId,address borrower,uint month, address _contractAddress) public { if(ES1.friendlyaddress(msg.sender) && (now >= Orders[_orderId].time * Orders[_orderId].borrows[borrower].duesPaid + 30 days)){ if(Orders[_orderId].borrows[borrower].duesPaid < month && !ES1.isRegistrar(borrower) && !ES1.isUserLocked(borrower)){ wERC20 ecoToken = wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())); uint due = orderMonthlyDue(_orderId,borrower,1)*(10**uint(ecoToken.decimals())); uint fee = (due*ES1.rewardFee())/100; ES1.setUserLocked(borrower, true); ecoToken.mint(Orders[_orderId].creator,due-fee); ES1.setOwnerFeeVault(Orders[_orderId].token, fee); ecoToken.mint(Orders[_orderId].creator,due-fee); users[Orders[_orderId].creator].tokenYield[Orders[_orderId].token] += due - fee; Orders[_orderId].earnings += due -fee; YieldForTokens[Orders[_orderId].token] += due; ES1.emitDuePaid(_orderId,borrower,orderMonthlyDue(_orderId,borrower,1)); } if(Orders[_orderId].borrows[borrower].duesPaid != Orders[_orderId].borrows[borrower].duration){ scheduleCheck(_orderId,borrower,1,_contractAddress); } } } function orderMonthlyDue(uint64 _orderId, address _borrower,uint _duration) public view returns(uint){ if (Orders[_orderId].creator != address(0)) { (uint ecoPrice,uint tokenPrice ) = (fetchTokenPrice(ES1.WRAP_ECO_SYMBOL()), fetchTokenPrice(Orders[_orderId].token)); uint principle = (Orders[_orderId].borrows[_borrower].amount*_duration)/Orders[_orderId].borrows[_borrower].duration; uint tokendue = principle + (principle*Orders[_orderId].yield*_duration)/(100*Orders[_orderId].borrows[_borrower].duration); return (tokendue*tokenPrice)/ecoPrice; } } function borrowZero(uint _amount, string memory token, address userAddress, address _contractAddress) public { uint usdValue = _amount*fetchTokenPrice(token)/(10**8); require(getbuyPower(userAddress) >= usdValue,"power insufficient"); require(!ES1.isUserLocked(userAddress) && ES1.friendlyaddress(msg.sender), "UserLocked Pay Dues"); //users[userAddress].buyingPower -= usdValue; users[userAddress].borrows[token] += _amount; freeStorage memory newBorrow = freeStorage({ amount: _amount, time: now, wtoken: token, usdvalue: usdValue }); users[userAddress].myBorrows.push(newBorrow); uint amount = _amount*(10**uint(wERC20(ETM.getwTokenAddress(token)).decimals())); wERC20(ETM.getwTokenAddress(token)).mint(userAddress,amount); if(!ES1.isRegistrar(userAddress)){ scheduleCheck(0,userAddress,1,_contractAddress); } } function zeroDepositorPop(address userAddress, string memory _tokenSymbol, uint _amount) public { require(ES1.friendlyaddress(msg.sender),"Not Friendly Address"); if(users[userAddress].deposits[_tokenSymbol]>0) { uint tokenUsdValue = _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].deposits[_tokenSymbol] -= _amount; users[userAddress].totalDeposit -= tokenUsdValue; uint amountLeft= _amount; uint counter = users[userAddress].myDeposits.length; for( uint i= counter-1; amountLeft >0 ; i--){ if (users[userAddress].myDeposits[i].amount < amountLeft){ amountLeft -= users[userAddress].myDeposits[i].amount; issueReward(userAddress, _tokenSymbol, users[userAddress].myDeposits[i].time, users[userAddress].myDeposits[i].amount*fetchTokenPrice(_tokenSymbol)/(10**8)); users[userAddress].myDeposits.pop(); } else { users[userAddress].myDeposits[i].amount -= amountLeft; issueReward(userAddress, _tokenSymbol, users[userAddress].myDeposits[i].time, amountLeft*fetchTokenPrice(_tokenSymbol)/(10**8)); amountLeft = 0; } } } } function zeroBorrowPop(address userAddress, string memory _tokenSymbol, uint _amount) public returns (uint) { require(ES1.friendlyaddress(msg.sender),"Not Friendly Address"); if(users[userAddress].borrows[_tokenSymbol]>0) { uint tokenUsdValue = _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].borrows[_tokenSymbol] -= _amount; users[userAddress].totalBorrowed -= tokenUsdValue; uint amountLeft= _amount; uint dues; uint counter = users[userAddress].myBorrows.length; for( uint i= counter-1; amountLeft >0 ; i--){ if (users[userAddress].myBorrows[i].amount < amountLeft){ uint a = users[userAddress].myBorrows[i].amount; amountLeft -= a; dues+= calculateECOEarning(a*fetchTokenPrice(_tokenSymbol)/(10**8), _tokenSymbol, users[userAddress].myBorrows[i].time); users[userAddress].myBorrows.pop(); } else { users[userAddress].myDeposits[i].amount -= amountLeft; dues += calculateECOEarning(amountLeft*fetchTokenPrice(_tokenSymbol)/(10**8), _tokenSymbol, users[userAddress].myBorrows[i].time); amountLeft = 0; } } ES1.setOwnerFeeVault(_tokenSymbol, (dues*ES1.rewardFee()/100)); return (dues*(ES1.rewardFee()+100)/100); } } function issueReward(address userAddress, string memory _tokenSymbol, uint time, uint tokenUsdValue) internal { wERC20 ecoToken = wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())); uint reward = calculateECOEarning(tokenUsdValue, _tokenSymbol, time); ecoToken.mint(userAddress, reward); } function calculateECOEarning(uint usdvalue, string memory _tokenSymbol, uint time) private view returns (uint){ uint _amount = usdvalue*fetchTokenPrice(ES1.WRAP_ECO_SYMBOL()); uint reward = (_amount * ES1.slabRateDeposit(_tokenSymbol) * (time - now))/3155695200; //decimal from Abacus is setoff by decimal from Eco return reward; } function getECOEarnings(address userAddress) public view returns (uint){ uint ecobalance; for(uint i=1; i<users[userAddress].myDeposits.length && i<users[userAddress].myBorrows.length; i++) { ecobalance += calculateECOEarning(users[userAddress].myDeposits[i].usdvalue, users[userAddress].myDeposits[i].wtoken, users[userAddress].myDeposits[i].time); ecobalance -= calculateECOEarning(users[userAddress].myBorrows[i].usdvalue, users[userAddress].myBorrows[i].wtoken, users[userAddress].myBorrows[i].time); } return ecobalance - users[userAddress].ecoWithdrawls; } function redeemEcoEarning(address userAddress, uint amount) external { require(ES1.friendlyaddress(msg.sender),"Not Friendly Address"); users[userAddress].ecoWithdrawls += amount; } /*==============Helpers============ ---------------------------------*/ function getOrderIds() public view returns(uint [] memory){ return orderIds; } /*function getUserBorrowedOrders(address userAddress) public view returns(uint64 [] memory borrowedOrders){ return users[userAddress].borrowedOrders; }*/ function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint64){ //Put any Token Wrapped or Direct return abacus.getJobResponse(ETM.getFetchId(_tokenSymbol))[0]; } } = 0;i<TokenAddresses.length;i++){ wERC20(TokenAddresses[i]).changeAdmin(ecoAddress); } } function addToken(address tokenAddress) public { require(msg.sender == owner); ERC20Basic token = ERC20Basic(tokenAddress); require(getrTokenAddress(token.symbol())== address(0),"token exist"); rTokens[token.symbol()] = tokenAddress; TokenAddresses.push(tokenAddress); } function createWrapToken(string memory name,string memory symbol,uint64 _fetchId,string memory wrapOf) public returns(address TokenAddress){ require(msg.sender == owner); require(EcoceliumAddress != address(0),"update Ecocelium Address"); ERC20Basic rToken = ERC20Basic(getrTokenAddress(wrapOf)); require(getrTokenAddress(wrapOf) != address(0),"counterpart not supported"); wERC20 token = new wERC20(name,symbol,uint8(rToken.decimals()),EcoceliumAddress,address(this)); // token.initialize(name,symbol,uint8(rToken.decimals()),EcoceliumAddress,address(this)); rTokensTowToken[wrapOf] = symbol; TokenAddresses.push(address(token)); wTokens[symbol] = TokenConfig({ tokenAddress:address(token), fetchId : _fetchId }); emit WrapTokenCreated(address(token),name,symbol,token.decimals()); return address(token); } function changeOwner(address _owner) public{ require(owner == msg.sender); owner =_owner; } function getwTokenAddress(string memory symbol) public view returns(address){ return wTokens[symbol].tokenAddress; } function getFetchId(string memory symbol ) public view returns(uint64){ return wTokens[symbol].fetchId; } function getrTokenAddress(string memory symbol) public view returns(address){ return rTokens[symbol]; } function getTokenAddresses() public view returns(address[] memory){ return TokenAddresses; } function getWrapped(string memory symbol) public view returns(string memory){ return rTokensTowToken[symbol]; } function getTokenID(string memory symbol) public view returns(uint){ for(uint i=0; i< TokenAddresses.length; i++) { if(TokenAddresses[i] == wTokens[symbol].tokenAddress) { return i; } } } } contract EcoceliumSub1 is Initializable { address public owner; EcoceliumTokenManager ETM; string public WRAP_ECO_SYMBOL; uint public swapFee; uint public rewardFee; uint public tradeFee; uint public CDSpercent; string [] rtokenlist; string [] wtokenlist; mapping (string => uint) public rcurrencyID; mapping (string => uint) public wcurrencyID; mapping (address => bool) public isRegistrar; mapping (address => bool) public isUserLocked; mapping (string => uint ) public ownerFeeVault; mapping (string => uint) public slabRateDeposit; mapping (address => bool) public friendlyaddress; event OrderCreated( address userAddress, uint duration, uint yield, uint amount, string tok ); event Swap( address userAddress, string from, string to, uint amount ); event Borrowed( uint64 orderId, address borrower, uint amount, uint duration ); event Deposit( address userAddress, string token, uint tokenAmount, uint collateralValue ); event DuePaid( uint64 orderId, address borrower, uint amount ); function initializeAddress(address _owner) public initializer { owner = _owner; friendlyaddress[_owner] = true; } function addCurrency(string memory rtoken) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); if(rcurrencyID[rtoken] != 0) { rtokenlist.push(rtoken); rcurrencyID[rtoken] = rtokenlist.length+1; wtokenlist.push(ETM.getWrapped(rtoken)); wcurrencyID[ETM.getWrapped(rtoken)] = wtokenlist.length+1; } } function changeOwner(address _owner) public{ (msg.sender == owner,"not owner"); owner = _owner; } function setSlabRate(string memory WToken, uint rate) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); slabRateDeposit[WToken] = rate; } function setUserLocked(address userAddress, bool value) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); isUserLocked[userAddress] = value; } function setFriendlyAddress(address Address) public { (msg.sender == owner,"not owner"); friendlyaddress[Address] = true; } function addRegistrar(address _registrar) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); isRegistrar[_registrar] = true; } function setOwnerFeeVault(string memory add,uint value) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); ownerFeeVault[add] += value; } function emitOrderCreated(address userAddress, uint _duration, uint _yield, uint newAmount,string memory _tokenSymbol) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit OrderCreated(userAddress,_duration,_yield,newAmount,_tokenSymbol); } function emitSwap(address msgSender, string memory from, string memory to,uint _amount) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Swap(msgSender,from,to,_amount); } function emitBorrowed(uint64 _orderId, address msgSender, uint _amount,uint _duration) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Borrowed(_orderId,msgSender,_amount,_duration); } function emitDeposit(address msgSender, string memory _tokenSymbol, uint amount, uint tokenUsdValue) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Deposit(msgSender,_tokenSymbol,amount,tokenUsdValue); } function emitDuePaid(uint64 _orderId, address msgSender, uint due) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit DuePaid(_orderId,msgSender,due); } function setWRAP_ECO_SYMBOL(string memory _symbol) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); WRAP_ECO_SYMBOL = _symbol; } function updateFees(uint _swapFee,uint _tradeFee,uint _rewardFee) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); (swapFee,tradeFee,rewardFee) = (_swapFee,_tradeFee,_rewardFee); } function setCSDpercent(uint percent) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); CDSpercent = percent; } function unlockDeposit(address _userAddress, uint amount, string memory WToken) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); wERC20 wtoken = wERC20(ETM.getwTokenAddress(WToken)); wtoken.release(_userAddress,amount); } } ETM = EcoceliumTokenManager(ETMaddress); } function changeAbacusaddress(address Abacusaddress) public{ require(msg.sender == owner,"not owner"); abacus = IAbacusOracle(Abacusaddress); } function changeESaddress(address ESaddress) public{ require(msg.sender == owner,"not owner"); ES = EcoceliumSub(ESaddress); } function changeES1address(address ES1address) public{ require(msg.sender == owner,"not owner"); ES1 = EcoceliumSub1(ES1address); } function changeOwner(address _owner) public{ require(msg.sender==owner); owner = _owner; } /*===========Main functions============ -------------------------------------*/ function Deposit(string memory rtoken, uint _amount) external { address _msgSender = msg.sender; address _contractAddress = address(this); string memory wtoken = ETM.getWrapped(rtoken); uint amount = _deposit(rtoken, _amount, _msgSender, _contractAddress, wtoken); ES.zeroDepositorPush(_msgSender, wtoken, _amount); wERC20(ETM.getwTokenAddress(ETM.getWrapped(rtoken))).mint(_msgSender, amount); wERC20(ETM.getwTokenAddress(ETM.getWrapped(rtoken))).lock(_msgSender, amount); } function _deposit(string memory rtoken,uint _amount, address msgSender, address _contractAddress, string memory wtoken) internal returns(uint) { require(ETM.getrTokenAddress(rtoken) != address(0) && ETM.getwTokenAddress(wtoken) != address(0),"not supported"); (wERC20 wToken,ERC20Basic rToken)=(wERC20(ETM.getwTokenAddress(wtoken)),ERC20Basic(ETM.getrTokenAddress(rtoken))); uint amount = _amount*(10**uint(wToken.decimals())); require(rToken.allowance(msgSender,_contractAddress) >= amount,"set allowance"); rToken.transferFrom(msgSender,_contractAddress,amount); ES1.emitSwap(msgSender,rtoken,wtoken,_amount); return amount; } function depositAndOrder(address userAddress,string memory rtoken ,uint _amount,uint _duration,uint _yield) external { require(msg.sender == userAddress); _deposit(rtoken, _amount, userAddress, address(this), ETM.getWrapped(rtoken)); ES.createOrder(userAddress, ETM.getWrapped(rtoken), _amount, _duration, _yield, address(this)); } function createOrder(address userAddress,string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield) public { require(msg.sender == userAddress); string memory wtoken = ETM.getWrapped(_tokenSymbol); if(ES.getUserDepositsbyToken(userAddress, wtoken) > _amount ) { ES.zeroDepositorPop(userAddress, wtoken , _amount); ES.createOrder(userAddress, wtoken, _amount, _duration, _yield, address(this)); } } function getAggEcoBalance(address userAddress) public view returns(uint) { return wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())).balanceOf(userAddress) + ES.getECOEarnings(userAddress); } function _borrowOrder(uint64 _orderId, uint _amount, uint _duration) public { ES.borrow(_orderId,_amount,_duration,msg.sender,address(this)); } function payDueOrder(uint64 _orderId,uint _duration) external{ ES.payDue(_orderId,_duration,msg.sender); } function clearBorrow(string memory rtoken, uint _amount) external{ address msgSender = msg.sender; address _contractAddress = address(this); string memory wtoken = ETM.getWrapped(rtoken); require(ETM.getrTokenAddress(rtoken) != address(0) && ETM.getwTokenAddress(wtoken) != address(0),"not supported"); (wERC20 wToken,ERC20Basic rToken)=(wERC20(ETM.getwTokenAddress(wtoken)),ERC20Basic(ETM.getrTokenAddress(rtoken))); uint amount = _amount*(10**uint(wToken.decimals())); require(rToken.allowance(msgSender,_contractAddress) >= amount,"set allowance"); rToken.transferFrom(msgSender,_contractAddress,amount); uint dues = ES.zeroBorrowPop(msgSender, wtoken, _amount); ERC20Basic(ETM.getrTokenAddress(ECO)).transferFrom(msgSender, _contractAddress, dues); } function Borrow(uint _amount, string memory _tokenSymbol) public { ES.borrowZero(_amount, ETM.getWrapped(_tokenSymbol) ,msg.sender,address(this)); } function SwapWrapToWrap(string memory token1,string memory token2, uint token1amount) external returns(uint) { address msgSender = msg.sender; (uint token1price,uint token2price) = (fetchTokenPrice(token1),fetchTokenPrice(token2)); uint token2amount = (token1amount*token1price*(100-ES1.swapFee()))/token2price/100; (wERC20 Token1,wERC20 Token2) = (wERC20(ETM.getwTokenAddress(token1)),wERC20(ETM.getwTokenAddress(token2))); ES1.unlockDeposit(msgSender, token1amount, token1); Token1.burnFrom(msgSender,token1amount*(10**uint(Token1.decimals()))); ES.zeroDepositorPop(msgSender,token1,token1amount); Token2.mint(msgSender,token2amount*(10**uint(Token2.decimals()))); Token2.lock(msgSender, token2amount*(10**uint(Token2.decimals()))); ES1.setOwnerFeeVault(token1, token1price*ES1.swapFee()/100); ES.zeroDepositorPush(msgSender, token2,token2amount); ES1.emitSwap(msgSender,token1,token2,token2amount); return token2amount; } function orderExpired(uint64 _orderId) external { ES.orderExpired(_orderId); } function dueCheck(uint64 _orderId,address borrower,uint month) external { ES.dueCheck(_orderId,borrower,month,address(this)); } function cancelOrder(uint64 _orderId) public{ ES.cancelOrder(_orderId); } receive() external payable { } /*==============Helpers============ ---------------------------------*/ function orderMonthlyDue(uint64 _orderId, address _borrower,uint _duration) public view returns(uint){ return ES.orderMonthlyDue(_orderId,_borrower,_duration); } function updateFees(uint _swapFee,uint _tradeFee,uint _rewardFee) public{ require(msg.sender == owner); ES1.updateFees(_swapFee,_tradeFee,_rewardFee); } function setCSDpercent(uint percent) public { require(msg.sender == owner); ES1.setCSDpercent(percent); } function setWRAP_ECO_SYMBOL(string memory _symbol) internal { require(msg.sender == owner); ECO = _symbol; ES1.setWRAP_ECO_SYMBOL(_symbol); } function getOrderIds() public view returns(uint [] memory){ return ES.getOrderIds(); } // function getOrder( uint64 investmentId) public view returns(uint time, uint duration, uint amount, uint yield, string memory token, Status isActive){ // return (Orders[investmentId].time,Orders[investmentId].duration,Orders[investmentId].amount,Orders[investmentId].yield,Orders[investmentId].token,Orders[investmentId].status); // } /*function getUserBorrowedOrders(address userAddress) public view returns(uint64 [] memory borrowedOrders){ return ES.getUserBorrowedOrders(userAddress); } */ /*function getBorrowersOfOrder(uint64 _orderId) public view returns(address[] memory borrowers){ return ES.getBorrowersOfOrder(_orderId); } function getBorrowDetails(uint64 _orderId,address borrower) public view returns(uint amount,uint duration,uint dated,uint _duesPaid ){ (amount,duration,dated,_duesPaid)=ES.getBorrowDetails(_orderId,borrower); return (amount,duration,dated,_duesPaid); } */ function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint64){ return ES.fetchTokenPrice(_tokenSymbol); } /*function isWithdrawEligible(address _msgSender, string memory _token, uint _amount) public view returns (bool) { require(msg.sender == owner); //to be written uint tokenUsdValue = _amount*fetchTokenPrice(_token)/(10**8); uint buypower = ES.getbuyPower(_msgSender); if((buypower*(100+ES1.CDSpercent())/100) > tokenUsdValue ) return true; }*/ function Withdraw(string memory to, uint _amount) external { address msgSender = msg.sender; string memory from = ETM.getWrapped(to); require(ETM.getwTokenAddress(from) != address(0) && ETM.getrTokenAddress(to) != address(0),"not supported"); require(!ES1.isUserLocked(msgSender), "Your Address is Locked Pay Dues"); //require(isWithdrawEligible(msgSender, to, _amount) , "Not Eligible for Withdraw"); require(((ES.getbuyPower(msgSender)*(100+ES1.CDSpercent())/100) > (_amount*fetchTokenPrice(to)/(10**8)) ), "Not Eligible for Withdraw"); wERC20 wToken = wERC20(ETM.getwTokenAddress(to)); uint amount = _amount*(10**uint(wToken.decimals())); uint amountLeft; if(keccak256(abi.encodePacked(to)) == keccak256(abi.encodePacked(ES1.WRAP_ECO_SYMBOL()))) { require(wToken.balanceOf(msgSender) + ES.getECOEarnings(msgSender) >= amount,"Insufficient Balance"); if(wToken.balanceOf(msgSender)>=amount) { _withdraw(msgSender, from, amount, to, _amount); } else { if(wToken.balanceOf(msgSender)<amount) amountLeft = amount - wToken.balanceOf(msgSender); _withdraw(msgSender, from, wToken.balanceOf(msgSender), to, (wToken.balanceOf(msgSender)/(10**uint(wToken.decimals())))); ES.redeemEcoEarning(msgSender,amountLeft); } } else { //uint locked = ES.getUserLockedAmount(from, msgSender); require(wToken.balanceOf(msgSender) >= amount,"Insufficient Balance"); _withdraw(msgSender, from, amount, to, _amount); } ES1.emitSwap(msgSender,from,to,_amount); } function _withdraw(address msgSender, string memory from, uint amount, string memory to, uint _amount ) internal { (wERC20 wToken,ERC20Basic rToken) = (wERC20(ETM.getwTokenAddress(to)),ERC20Basic(ETM.getrTokenAddress(from))); ES1.unlockDeposit(msgSender,amount, from); wToken.burnFrom(msgSender,amount); ES1.setOwnerFeeVault(to,(amount*ES1.swapFee())/100); ES.zeroDepositorPop(msgSender,from,_amount); uint newAmount = amount - (amount*ES1.swapFee())/100; rToken.transfer(msgSender,newAmount); } }
0x6080604052600436106101855760003560e01c80635d130ec6116100d1578063ac51e38e1161008a578063d4001a0511610064578063d4001a0514610aa2578063e364db9214610ad5578063f7f56d6314610b1d578063fd950f7514610c555761018c565b8063ac51e38e1461097e578063bc01b2ba14610a36578063cf2a916014610a6f5761018c565b80635d130ec614610783578063665e6ffa14610858578063843b4968146108825780638da5cb5b146108b55780639e0acf8f146108e6578063a6f9dae11461094b5761018c565b80631d16d2941161013e5780634374df56116101185780634374df561461062d578063523eb5371461066c578063591e68551461069f57806359f83370146106f95761018c565b80631d16d294146104f7578063224290851461052a57806334f2f388146105605761018c565b80630403493c146101915780630e900fa41461025f578063100cda351461029257806310d7c0d1146103455780631352900014610411578063151230e3146104c45761018c565b3661018c57005b600080fd5b34801561019d57600080fd5b5061025d600480360360a08110156101b457600080fd5b6001600160a01b038235169190810190604081016020820135600160201b8111156101de57600080fd5b8201836020820111156101f057600080fd5b803590602001918460018302840111600160201b8311171561021157600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505082359350505060208101359060400135610d08565b005b34801561026b57600080fd5b5061025d6004803603602081101561028257600080fd5b50356001600160a01b0316611194565b34801561029e57600080fd5b5061025d600480360360408110156102b557600080fd5b810190602081018135600160201b8111156102cf57600080fd5b8201836020820111156102e157600080fd5b803590602001918460018302840111600160201b8311171561030257600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505091359250611201915050565b34801561035157600080fd5b5061025d600480360360a081101561036857600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561039257600080fd5b8201836020820111156103a457600080fd5b803590602001918460018302840111600160201b831117156103c557600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505082359350505060208101359060400135611b7e565b34801561041d57600080fd5b5061025d6004803603604081101561043457600080fd5b810190602081018135600160201b81111561044e57600080fd5b82018360208201111561046057600080fd5b803590602001918460018302840111600160201b8311171561048157600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505091359250611fcf915050565b3480156104d057600080fd5b5061025d600480360360208110156104e757600080fd5b50356001600160401b03166127d6565b34801561050357600080fd5b5061025d6004803603602081101561051a57600080fd5b50356001600160a01b0316612846565b34801561053657600080fd5b5061025d6004803603606081101561054d57600080fd5b50803590602081013590604001356128b3565b34801561056c57600080fd5b506106116004803603602081101561058357600080fd5b810190602081018135600160201b81111561059d57600080fd5b8201836020820111156105af57600080fd5b803590602001918460018302840111600160201b831117156105d057600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612942945050505050565b604080516001600160401b039092168252519081900360200190f35b34801561063957600080fd5b5061025d6004803603606081101561065057600080fd5b506001600160401b038135169060208101359060400135612a1c565b34801561067857600080fd5b5061025d6004803603602081101561068f57600080fd5b50356001600160401b0316612a8b565b3480156106ab57600080fd5b506106e7600480360360608110156106c257600080fd5b506001600160401b03813516906001600160a01b036020820135169060400135612ae0565b60408051918252519081900360200190f35b34801561070557600080fd5b5061070e612b7b565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610748578181015183820152602001610730565b50505050905090810190601f1680156107755780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61025d600480360360c081101561079957600080fd5b6001600160a01b03823581169260208101358216926040820135831692606083013581169260808101359091169181019060c0810160a0820135600160201b8111156107e457600080fd5b8201836020820111156107f657600080fd5b803590602001918460018302840111600160201b8311171561081757600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612c09945050505050565b34801561086457600080fd5b5061025d6004803603602081101561087b57600080fd5b5035612d87565b34801561088e57600080fd5b5061025d600480360360208110156108a557600080fd5b50356001600160a01b0316612deb565b3480156108c157600080fd5b506108ca612e58565b604080516001600160a01b039092168252519081900360200190f35b3480156108f257600080fd5b506108fb612e67565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561093757818101518382015260200161091f565b505050509050019250505060405180910390f35b34801561095757600080fd5b5061025d6004803603602081101561096e57600080fd5b50356001600160a01b0316612f78565b34801561098a57600080fd5b5061025d600480360360408110156109a157600080fd5b81359190810190604081016020820135600160201b8111156109c257600080fd5b8201836020820111156109d457600080fd5b803590602001918460018302840111600160201b831117156109f557600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612fb1945050505050565b348015610a4257600080fd5b5061025d60048036036040811015610a5957600080fd5b506001600160401b03813516906020013561322b565b348015610a7b57600080fd5b5061025d60048036036020811015610a9257600080fd5b50356001600160a01b031661328d565b348015610aae57600080fd5b506106e760048036036020811015610ac557600080fd5b50356001600160a01b03166132fa565b348015610ae157600080fd5b5061025d60048036036060811015610af857600080fd5b506001600160401b03813516906001600160a01b0360208201351690604001356135f3565b348015610b2957600080fd5b506106e760048036036060811015610b4057600080fd5b810190602081018135600160201b811115610b5a57600080fd5b820183602082011115610b6c57600080fd5b803590602001918460018302840111600160201b83111715610b8d57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b811115610bdf57600080fd5b820183602082011115610bf157600080fd5b803590602001918460018302840111600160201b83111715610c1257600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550509135925061365d915050565b348015610c6157600080fd5b5061025d60048036036040811015610c7857600080fd5b810190602081018135600160201b811115610c9257600080fd5b820183602082011115610ca457600080fd5b803590602001918460018302840111600160201b83111715610cc557600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092955050913592506140e8915050565b336001600160a01b03861614610d1d57600080fd5b603554604051630573295560e21b81526020600482018181528751602484015287516060946001600160a01b0316936315cca554938a939283926044019185019080838360005b83811015610d7c578181015183820152602001610d64565b50505050905090810190601f168015610da95780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b158015610dc657600080fd5b505afa158015610dda573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015610e0357600080fd5b8101908080516040519392919084600160201b821115610e2257600080fd5b908301906020820185811115610e3757600080fd5b8251600160201b811182820188101715610e5057600080fd5b82525081516020918201929091019080838360005b83811015610e7d578181015183820152602001610e65565b50505050905090810190601f168015610eaa5780820380516001836020036101000a031916815260200191505b506040818152603654630ecb81fb60e11b83526001600160a01b038d811660048501908152602485019384528851604486015288519899508c98919092169650631d9703f695508d9450889391929160640190602085019080838360005b83811015610f20578181015183820152602001610f08565b50505050905090810190601f168015610f4d5780820380516001836020036101000a031916815260200191505b50935050505060206040518083038186803b158015610f6b57600080fd5b505afa158015610f7f573d6000803e3d6000fd5b505050506040513d6020811015610f9557600080fd5b5051111561118c57603654604051632a8fa4af60e21b81526001600160a01b038881166004830190815260448301889052606060248401908152855160648501528551929094169363aa3e92bc938b9387938b9390929091608490910190602086019080838360005b83811015611016578181015183820152602001610ffe565b50505050905090810190601f1680156110435780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b15801561106457600080fd5b505af1158015611078573d6000803e3d6000fd5b50505050603660009054906101000a90046001600160a01b03166001600160a01b0316631ceb9f578783878787306040518763ffffffff1660e01b815260040180876001600160a01b0316815260200180602001868152602001858152602001848152602001836001600160a01b03168152602001828103825287818151815260200191508051906020019080838360005b8381101561112257818101518382015260200161110a565b50505050905090810190601f16801561114f5780820380516001836020036101000a031916815260200191505b50975050505050505050600060405180830381600087803b15801561117357600080fd5b505af1158015611187573d6000803e3d6000fd5b505050505b505050505050565b6033546001600160a01b031633146111df576040805162461bcd60e51b81526020600482015260096024820152683737ba1037bbb732b960b91b604482015290519081900360640190fd5b603680546001600160a01b0319166001600160a01b0392909216919091179055565b603554604051630573295560e21b8152602060048201818152855160248401528551339430946060946001600160a01b03909216936315cca554938a93919283926044909101919085019080838360005b8381101561126a578181015183820152602001611252565b50505050905090810190601f1680156112975780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b1580156112b457600080fd5b505afa1580156112c8573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156112f157600080fd5b8101908080516040519392919084600160201b82111561131057600080fd5b90830190602082018581111561132557600080fd5b8251600160201b81118282018810171561133e57600080fd5b82525081516020918201929091019080838360005b8381101561136b578181015183820152602001611353565b50505050905090810190601f1680156113985780820380516001836020036101000a031916815260200191505b506040819052603554636e6164d760e01b82526020600483018181528c5160248501528c519798506000976001600160a01b039093169650636e6164d795508c94509283926044909101918501908083838b5b838110156114035781810151838201526020016113eb565b50505050905090810190601f1680156114305780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561144d57600080fd5b505afa158015611461573d6000803e3d6000fd5b505050506040513d602081101561147757600080fd5b50516001600160a01b03161480159061156b575060355460405163383a1caf60e21b81526020600482018181528451602484015284516000946001600160a01b03169363e0e872bc938793928392604401918501908083838b5b838110156114e95781810151838201526020016114d1565b50505050905090810190601f1680156115165780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561153357600080fd5b505afa158015611547573d6000803e3d6000fd5b505050506040513d602081101561155d57600080fd5b50516001600160a01b031614155b6115ac576040805162461bcd60e51b815260206004820152600d60248201526c1b9bdd081cdd5c1c1bdc9d1959609a1b604482015290519081900360640190fd5b60355460405163383a1caf60e21b815260206004820181815284516024840152845160009485946001600160a01b039091169363e0e872bc93889390928392604490910191908501908083838b5b838110156116125781810151838201526020016115fa565b50505050905090810190601f16801561163f5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561165c57600080fd5b505afa158015611670573d6000803e3d6000fd5b505050506040513d602081101561168657600080fd5b5051603554604051636e6164d760e01b81526020600482018181528b5160248401528b516001600160a01b0390941693636e6164d7938d9383926044909201919085019080838360005b838110156116e85781810151838201526020016116d0565b50505050905090810190601f1680156117155780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561173257600080fd5b505afa158015611746573d6000803e3d6000fd5b505050506040513d602081101561175c57600080fd5b50516040805163313ce56760e01b815290519294509092506000916001600160a01b0385169163313ce567916004808301926020929190829003018186803b1580156117a757600080fd5b505afa1580156117bb573d6000803e3d6000fd5b505050506040513d60208110156117d157600080fd5b505160408051636eb1769f60e11b81526001600160a01b0389811660048301528881166024830152915160ff909316600a0a8a02935083929185169163dd62ed3e91604480820192602092909190829003018186803b15801561183357600080fd5b505afa158015611847573d6000803e3d6000fd5b505050506040513d602081101561185d57600080fd5b505110156118a2576040805162461bcd60e51b815260206004820152600d60248201526c73657420616c6c6f77616e636560981b604482015290519081900360640190fd5b816001600160a01b03166323b872dd8787846040518463ffffffff1660e01b815260040180846001600160a01b03168152602001836001600160a01b031681526020018281526020019350505050600060405180830381600087803b15801561190a57600080fd5b505af115801561191e573d6000803e3d6000fd5b5050603654604051630a80a2bd60e41b81526001600160a01b038a811660048301908152604483018d90526060602484019081528a5160648501528a516000975092909416945063a80a2bd0938c938b938f9392916084019060208601908083838d5b83811015611999578181015183820152602001611981565b50505050905090810190601f1680156119c65780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b1580156119e757600080fd5b505af11580156119fb573d6000803e3d6000fd5b505050506040513d6020811015611a1157600080fd5b5051603554604051636e6164d760e01b81526020600482019081526038805460026000196001831615610100020190911604602484018190529495506001600160a01b0390931693636e6164d79392829160449091019084908015611ab75780601f10611a8c57610100808354040283529160200191611ab7565b820191906000526020600020905b815481529060010190602001808311611a9a57829003601f168201915b50509250505060206040518083038186803b158015611ad557600080fd5b505afa158015611ae9573d6000803e3d6000fd5b505050506040513d6020811015611aff57600080fd5b5051604080516323b872dd60e01b81526001600160a01b038a81166004830152898116602483015260448201859052915191909216916323b872dd91606480830192600092919082900301818387803b158015611b5b57600080fd5b505af1158015611b6f573d6000803e3d6000fd5b50505050505050505050505050565b336001600160a01b03861614611b9357600080fd5b603554604051630573295560e21b8152602060048201818152875160248401528751611d3994899489948c9430946001600160a01b03909416936315cca55493899383926044909201919085019080838360005b83811015611bff578181015183820152602001611be7565b50505050905090810190601f168015611c2c5780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b158015611c4957600080fd5b505afa158015611c5d573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015611c8657600080fd5b8101908080516040519392919084600160201b821115611ca557600080fd5b908301906020820185811115611cba57600080fd5b8251600160201b811182820188101715611cd357600080fd5b82525081516020918201929091019080838360005b83811015611d00578181015183820152602001611ce8565b50505050905090810190601f168015611d2d5780820380516001836020036101000a031916815260200191505b50604052505050615122565b50603654603554604051630573295560e21b81526020600482018181528851602484015288516001600160a01b0395861695631ceb9f57958c959116936315cca554938c93909283926044909101919085019080838360005b83811015611daa578181015183820152602001611d92565b50505050905090810190601f168015611dd75780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b158015611df457600080fd5b505afa158015611e08573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015611e3157600080fd5b8101908080516040519392919084600160201b821115611e5057600080fd5b908301906020820185811115611e6557600080fd5b8251600160201b811182820188101715611e7e57600080fd5b82525081516020918201929091019080838360005b83811015611eab578181015183820152602001611e93565b50505050905090810190601f168015611ed85780820380516001836020036101000a031916815260200191505b50604052505050868686306040518763ffffffff1660e01b815260040180876001600160a01b0316815260200180602001868152602001858152602001848152602001836001600160a01b03168152602001828103825287818151815260200191508051906020019080838360005b83811015611f5f578181015183820152602001611f47565b50505050905090810190601f168015611f8c5780820380516001836020036101000a031916815260200191505b50975050505050505050600060405180830381600087803b158015611fb057600080fd5b505af1158015611fc4573d6000803e3d6000fd5b505050505050505050565b603554604051630573295560e21b8152602060048201818152855160248401528551339430946060946001600160a01b03909216936315cca554938a93919283926044909101919085019080838360005b83811015612038578181015183820152602001612020565b50505050905090810190601f1680156120655780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b15801561208257600080fd5b505afa158015612096573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156120bf57600080fd5b8101908080516040519392919084600160201b8211156120de57600080fd5b9083019060208201858111156120f357600080fd5b8251600160201b81118282018810171561210c57600080fd5b82525081516020918201929091019080838360005b83811015612139578181015183820152602001612121565b50505050905090810190601f1680156121665780820380516001836020036101000a031916815260200191505b506040525050509050600061217e8686868686615122565b60365460405163d006617160e01b81526001600160a01b0387811660048301908152604483018a9052606060248401908152875160648501528751959650919093169363d006617193899388938c93909160840190602086019080838360005b838110156121f65781810151838201526020016121de565b50505050905090810190601f1680156122235780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b15801561224457600080fd5b505af1158015612258573d6000803e3d6000fd5b5050603554604051630573295560e21b81526020600482018181528b5160248401528b516001600160a01b03909416955063e0e872bc945085936315cca554938d9383926044909201919085019080838360005b838110156122c45781810151838201526020016122ac565b50505050905090810190601f1680156122f15780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b15801561230e57600080fd5b505afa158015612322573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561234b57600080fd5b8101908080516040519392919084600160201b82111561236a57600080fd5b90830190602082018581111561237f57600080fd5b8251600160201b81118282018810171561239857600080fd5b82525081516020918201929091019080838360005b838110156123c55781810151838201526020016123ad565b50505050905090810190601f1680156123f25780820380516001836020036101000a031916815260200191505b506040525050506040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561244557818101518382015260200161242d565b50505050905090810190601f1680156124725780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561248f57600080fd5b505afa1580156124a3573d6000803e3d6000fd5b505050506040513d60208110156124b957600080fd5b5051604080516340c10f1960e01b81526001600160a01b03878116600483015260248201859052915191909216916340c10f1991604480830192600092919082900301818387803b15801561250d57600080fd5b505af1158015612521573d6000803e3d6000fd5b5050603554604051630573295560e21b81526020600482018181528b5160248401528b516001600160a01b03909416955063e0e872bc945085936315cca554938d9383926044909201919085019080838360005b8381101561258d578181015183820152602001612575565b50505050905090810190601f1680156125ba5780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b1580156125d757600080fd5b505afa1580156125eb573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561261457600080fd5b8101908080516040519392919084600160201b82111561263357600080fd5b90830190602082018581111561264857600080fd5b8251600160201b81118282018810171561266157600080fd5b82525081516020918201929091019080838360005b8381101561268e578181015183820152602001612676565b50505050905090810190601f1680156126bb5780820380516001836020036101000a031916815260200191505b506040525050506040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561270e5781810151838201526020016126f6565b50505050905090810190601f16801561273b5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561275857600080fd5b505afa15801561276c573d6000803e3d6000fd5b505050506040513d602081101561278257600080fd5b50516040805163282d3fdf60e01b81526001600160a01b038781166004830152602482018590529151919092169163282d3fdf91604480830192600092919082900301818387803b15801561117357600080fd5b6036546040805163151230e360e01b81526001600160401b038416600482015290516001600160a01b039092169163151230e39160248082019260009290919082900301818387803b15801561282b57600080fd5b505af115801561283f573d6000803e3d6000fd5b5050505050565b6033546001600160a01b03163314612891576040805162461bcd60e51b81526020600482015260096024820152683737ba1037bbb732b960b91b604482015290519081900360640190fd5b603480546001600160a01b0319166001600160a01b0392909216919091179055565b6033546001600160a01b031633146128ca57600080fd5b60375460408051632242908560e01b815260048101869052602481018590526044810184905290516001600160a01b039092169163224290859160648082019260009290919082900301818387803b15801561292557600080fd5b505af1158015612939573d6000803e3d6000fd5b50505050505050565b60365460405163069e5e7160e31b81526020600482018181528451602484015284516000946001600160a01b0316936334f2f388938793928392604401918501908083838b5b838110156129a0578181015183820152602001612988565b50505050905090810190601f1680156129cd5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156129ea57600080fd5b505afa1580156129fe573d6000803e3d6000fd5b505050506040513d6020811015612a1457600080fd5b505192915050565b6036546040805163cbd1a5e760e01b81526001600160401b0386166004820152602481018590526044810184905233606482015230608482015290516001600160a01b039092169163cbd1a5e79160a48082019260009290919082900301818387803b15801561292557600080fd5b6036546040805163523eb53760e01b81526001600160401b038416600482015290516001600160a01b039092169163523eb5379160248082019260009290919082900301818387803b15801561282b57600080fd5b6036546040805163591e685560e01b81526001600160401b03861660048201526001600160a01b038581166024830152604482018590529151600093929092169163591e685591606480820192602092909190829003018186803b158015612b4757600080fd5b505afa158015612b5b573d6000803e3d6000fd5b505050506040513d6020811015612b7157600080fd5b5051949350505050565b6038805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015612c015780601f10612bd657610100808354040283529160200191612c01565b820191906000526020600020905b815481529060010190602001808311612be457829003601f168201915b505050505081565b600054610100900460ff1680612c225750612c22615809565b80612c30575060005460ff16155b612c6b5760405162461bcd60e51b815260040180806020018281038252602e815260200180615ec5602e913960400191505060405180910390fd5b600054610100900460ff16158015612c96576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b03808a166001600160a01b0319928316179092556035805489841690831681179091556034805489851690841681179091556036805489861690851617908190556037805489871695168517905560408051631767b57d60e31b815260048101949094526024840192909252604483019390935251919092169163bb3dabe891606480830192600092919082900301818387803b158015612d4157600080fd5b505af1158015612d55573d6000803e3d6000fd5b50508351612d6c9250603891506020850190615e31565b508015612939576000805461ff001916905550505050505050565b6033546001600160a01b03163314612d9e57600080fd5b6037546040805163332f37fd60e11b81526004810184905290516001600160a01b039092169163665e6ffa9160248082019260009290919082900301818387803b15801561282b57600080fd5b6033546001600160a01b03163314612e36576040805162461bcd60e51b81526020600482015260096024820152683737ba1037bbb732b960b91b604482015290519081900360640190fd5b603780546001600160a01b0319166001600160a01b0392909216919091179055565b6033546001600160a01b031681565b60365460408051639e0acf8f60e01b815290516060926001600160a01b031691639e0acf8f916004808301926000929190829003018186803b158015612eac57600080fd5b505afa158015612ec0573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015612ee957600080fd5b8101908080516040519392919084600160201b821115612f0857600080fd5b908301906020820185811115612f1d57600080fd5b82518660208202830111600160201b82111715612f3957600080fd5b82525081516020918201928201910280838360005b83811015612f66578181015183820152602001612f4e565b50505050905001604052505050905090565b6033546001600160a01b03163314612f8f57600080fd5b603380546001600160a01b0319166001600160a01b0392909216919091179055565b603654603554604051630573295560e21b81526020600482018181528551602484015285516001600160a01b039586169563fa61916d9589959116936315cca554938993909283926044909101919085019080838360005b83811015613021578181015183820152602001613009565b50505050905090810190601f16801561304e5780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b15801561306b57600080fd5b505afa15801561307f573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156130a857600080fd5b8101908080516040519392919084600160201b8211156130c757600080fd5b9083019060208201858111156130dc57600080fd5b8251600160201b8111828201881017156130f557600080fd5b82525081516020918201929091019080838360005b8381101561312257818101518382015260200161310a565b50505050905090810190601f16801561314f5780820380516001836020036101000a031916815260200191505b5060405250505033306040518563ffffffff1660e01b81526004018085815260200180602001846001600160a01b03168152602001836001600160a01b03168152602001828103825285818151815260200191508051906020019080838360005b838110156131c85781810151838201526020016131b0565b50505050905090810190601f1680156131f55780820380516001836020036101000a031916815260200191505b5095505050505050600060405180830381600087803b15801561321757600080fd5b505af115801561118c573d6000803e3d6000fd5b60365460408051634407f6c160e01b81526001600160401b03851660048201526024810184905233604482015290516001600160a01b0390921691634407f6c19160648082019260009290919082900301818387803b15801561321757600080fd5b6033546001600160a01b031633146132d8576040805162461bcd60e51b81526020600482015260096024820152683737ba1037bbb732b960b91b604482015290519081900360640190fd5b603580546001600160a01b0319166001600160a01b0392909216919091179055565b603654604080516331b3d0df60e01b81526001600160a01b038481166004830152915160009392909216916331b3d0df91602480820192602092909190829003018186803b15801561334b57600080fd5b505afa15801561335f573d6000803e3d6000fd5b505050506040513d602081101561337557600080fd5b50516035546037546040805160016238880b60e11b0319815290516001600160a01b039384169363e0e872bc93169163ff8eefea916004808301926000929190829003018186803b1580156133c957600080fd5b505afa1580156133dd573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561340657600080fd5b8101908080516040519392919084600160201b82111561342557600080fd5b90830190602082018581111561343a57600080fd5b8251600160201b81118282018810171561345357600080fd5b82525081516020918201929091019080838360005b83811015613480578181015183820152602001613468565b50505050905090810190601f1680156134ad5780820380516001836020036101000a031916815260200191505b506040525050506040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156135005781810151838201526020016134e8565b50505050905090810190601f16801561352d5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561354a57600080fd5b505afa15801561355e573d6000803e3d6000fd5b505050506040513d602081101561357457600080fd5b5051604080516370a0823160e01b81526001600160a01b038681166004830152915191909216916370a08231916024808301926020929190829003018186803b1580156135c057600080fd5b505afa1580156135d4573d6000803e3d6000fd5b505050506040513d60208110156135ea57600080fd5b50510192915050565b603654604080516301c3a97b60e41b81526001600160401b03861660048201526001600160a01b0385811660248301526044820185905230606483015291519190921691631c3a97b091608480830192600092919082900301818387803b15801561292557600080fd5b600033818061366b87612942565b61367487612942565b6001600160401b031691506001600160401b031691506000606482603760009054906101000a90046001600160a01b03166001600160a01b03166354cf2aeb6040518163ffffffff1660e01b815260040160206040518083038186803b1580156136dd57600080fd5b505afa1580156136f1573d6000803e3d6000fd5b505050506040513d602081101561370757600080fd5b5051606403858902028161371757fe5b048161371f57fe5b60355460405163383a1caf60e21b81526020600482018181528d5160248401528d5195909404955060009485946001600160a01b039094169363e0e872bc938f93919283926044909201918501908083838b5b8381101561378a578181015183820152602001613772565b50505050905090810190601f1680156137b75780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156137d457600080fd5b505afa1580156137e8573d6000803e3d6000fd5b505050506040513d60208110156137fe57600080fd5b505160355460405163383a1caf60e21b81526020600482018181528d5160248401528d516001600160a01b039094169363e0e872bc938f9383926044909201919085019080838360005b83811015613860578181015183820152602001613848565b50505050905090810190601f16801561388d5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156138aa57600080fd5b505afa1580156138be573d6000803e3d6000fd5b505050506040513d60208110156138d457600080fd5b810190808051906020019092919050505091509150603760009054906101000a90046001600160a01b03166001600160a01b031663e5361ea9878a8d6040518463ffffffff1660e01b815260040180846001600160a01b0316815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b83811015613971578181015183820152602001613959565b50505050905090810190601f16801561399e5780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b1580156139bf57600080fd5b505af11580156139d3573d6000803e3d6000fd5b50505050816001600160a01b03166379cc679087846001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015613a2057600080fd5b505afa158015613a34573d6000803e3d6000fd5b505050506040513d6020811015613a4a57600080fd5b5051604080516001600160e01b031960e086901b1681526001600160a01b03909316600484015260ff909116600a0a8c02602483015251604480830192600092919082900301818387803b158015613aa157600080fd5b505af1158015613ab5573d6000803e3d6000fd5b50505050603660009054906101000a90046001600160a01b03166001600160a01b031663aa3e92bc878c8b6040518463ffffffff1660e01b815260040180846001600160a01b0316815260200180602001838152602001828103825284818151815260200191508051906020019080838360005b83811015613b41578181015183820152602001613b29565b50505050905090810190601f168015613b6e5780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b158015613b8f57600080fd5b505af1158015613ba3573d6000803e3d6000fd5b50505050806001600160a01b03166340c10f1987836001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015613bf057600080fd5b505afa158015613c04573d6000803e3d6000fd5b505050506040513d6020811015613c1a57600080fd5b5051604080516001600160e01b031960e086901b1681526001600160a01b03909316600484015260ff909116600a0a8702602483015251604480830192600092919082900301818387803b158015613c7157600080fd5b505af1158015613c85573d6000803e3d6000fd5b50505050806001600160a01b031663282d3fdf87836001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015613cd257600080fd5b505afa158015613ce6573d6000803e3d6000fd5b505050506040513d6020811015613cfc57600080fd5b5051604080516001600160e01b031960e086901b1681526001600160a01b03909316600484015260ff909116600a0a8702602483015251604480830192600092919082900301818387803b158015613d5357600080fd5b505af1158015613d67573d6000803e3d6000fd5b5050603754604080516354cf2aeb60e01b815290516001600160a01b039092169350631a3aba9792508d9160649185916354cf2aeb91600480820192602092909190829003018186803b158015613dbd57600080fd5b505afa158015613dd1573d6000803e3d6000fd5b505050506040513d6020811015613de757600080fd5b5051890281613df257fe5b046040518363ffffffff1660e01b81526004018080602001838152602001828103825284818151815260200191508051906020019080838360005b83811015613e45578181015183820152602001613e2d565b50505050905090810190601f168015613e725780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015613e9257600080fd5b505af1158015613ea6573d6000803e3d6000fd5b505060365460405163d006617160e01b81526001600160a01b038a811660048301908152604483018990526060602484019081528f5160648501528f5192909416955063d006617194508b938f938a93608490910190602086019080838360005b83811015613f1f578181015183820152602001613f07565b50505050905090810190601f168015613f4c5780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b158015613f6d57600080fd5b505af1158015613f81573d6000803e3d6000fd5b50505050603760009054906101000a90046001600160a01b03166001600160a01b03166387c16782878c8c876040518563ffffffff1660e01b815260040180856001600160a01b031681526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b83811015614012578181015183820152602001613ffa565b50505050905090810190601f16801561403f5780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b8381101561407257818101518382015260200161405a565b50505050905090810190601f16801561409f5780820380516001836020036101000a031916815260200191505b509650505050505050600060405180830381600087803b1580156140c257600080fd5b505af11580156140d6573d6000803e3d6000fd5b50949c9b505050505050505050505050565b603554604051630573295560e21b815260206004820181815285516024840152855133946060946001600160a01b03909116936315cca554938993909283926044909101919085019080838360005b8381101561414f578181015183820152602001614137565b50505050905090810190601f16801561417c5780820380516001836020036101000a031916815260200191505b509250505060006040518083038186803b15801561419957600080fd5b505afa1580156141ad573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156141d657600080fd5b8101908080516040519392919084600160201b8211156141f557600080fd5b90830190602082018581111561420a57600080fd5b8251600160201b81118282018810171561422357600080fd5b82525081516020918201929091019080838360005b83811015614250578181015183820152602001614238565b50505050905090810190601f16801561427d5780820380516001836020036101000a031916815260200191505b50604081905260355463383a1caf60e21b82526020600483018181528751602485015287519798506000976001600160a01b03909316965063e0e872bc95508894509283926044909101918501908083838b5b838110156142e85781810151838201526020016142d0565b50505050905090810190601f1680156143155780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561433257600080fd5b505afa158015614346573d6000803e3d6000fd5b505050506040513d602081101561435c57600080fd5b50516001600160a01b0316148015906144505750603554604051636e6164d760e01b81526020600482018181528751602484015287516000946001600160a01b031693636e6164d7938a93928392604401918501908083838b5b838110156143ce5781810151838201526020016143b6565b50505050905090810190601f1680156143fb5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561441857600080fd5b505afa15801561442c573d6000803e3d6000fd5b505050506040513d602081101561444257600080fd5b50516001600160a01b031614155b614491576040805162461bcd60e51b815260206004820152600d60248201526c1b9bdd081cdd5c1c1bdc9d1959609a1b604482015290519081900360640190fd5b603754604080516330d0050560e01b81526001600160a01b038581166004830152915191909216916330d00505916024808301926020929190829003018186803b1580156144de57600080fd5b505afa1580156144f2573d6000803e3d6000fd5b505050506040513d602081101561450857600080fd5b50511561455c576040805162461bcd60e51b815260206004820152601f60248201527f596f75722041646472657373206973204c6f636b656420506179204475657300604482015290519081900360640190fd5b6305f5e10061456a85612942565b6001600160401b031684028161457c57fe5b046064603760009054906101000a90046001600160a01b03166001600160a01b031663cd68ea196040518163ffffffff1660e01b815260040160206040518083038186803b1580156145cd57600080fd5b505afa1580156145e1573d6000803e3d6000fd5b505050506040513d60208110156145f757600080fd5b50516036546040805163559fde5160e01b81526001600160a01b0388811660048301529151606490940193919092169163559fde51916024808301926020929190829003018186803b15801561464c57600080fd5b505afa158015614660573d6000803e3d6000fd5b505050506040513d602081101561467657600080fd5b5051028161468057fe5b04116146d3576040805162461bcd60e51b815260206004820152601960248201527f4e6f7420456c696769626c6520666f7220576974686472617700000000000000604482015290519081900360640190fd5b60355460405163383a1caf60e21b81526020600482018181528751602484015287516000946001600160a01b03169363e0e872bc938a93928392604401918501908083838b5b83811015614731578181015183820152602001614719565b50505050905090810190601f16801561475e5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561477b57600080fd5b505afa15801561478f573d6000803e3d6000fd5b505050506040513d60208110156147a557600080fd5b50516040805163313ce56760e01b815290519192506000916001600160a01b0384169163313ce567916004808301926020929190829003018186803b1580156147ed57600080fd5b505afa158015614801573d6000803e3d6000fd5b505050506040513d602081101561481757600080fd5b50516037546040805160016238880b60e11b03198152905160ff909316600a0a880293506000926001600160a01b039092169163ff8eefea916004808201928692909190829003018186803b15801561486f57600080fd5b505afa158015614883573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156148ac57600080fd5b8101908080516040519392919084600160201b8211156148cb57600080fd5b9083019060208201858111156148e057600080fd5b8251600160201b8111828201881017156148f957600080fd5b82525081516020918201929091019080838360005b8381101561492657818101518382015260200161490e565b50505050905090810190601f1680156149535780820380516001836020036101000a031916815260200191505b506040525050506040516020018082805190602001908083835b6020831061498c5780518252601f19909201916020918201910161496d565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405160208183030381529060405280519060200120876040516020018082805190602001908083835b602083106149fa5780518252601f1990920191602091820191016149db565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052805190602001201415614ef357603654604080516331b3d0df60e01b81526001600160a01b0388811660048301529151859392909216916331b3d0df91602480820192602092909190829003018186803b158015614a8b57600080fd5b505afa158015614a9f573d6000803e3d6000fd5b505050506040513d6020811015614ab557600080fd5b5051604080516370a0823160e01b81526001600160a01b0389811660048301529151918716916370a0823191602480820192602092909190829003018186803b158015614b0157600080fd5b505afa158015614b15573d6000803e3d6000fd5b505050506040513d6020811015614b2b57600080fd5b5051011015614b78576040805162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742042616c616e636560601b604482015290519081900360640190fd5b81836001600160a01b03166370a08231876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015614bc657600080fd5b505afa158015614bda573d6000803e3d6000fd5b505050506040513d6020811015614bf057600080fd5b505110614c0957614c048585848a8a61580f565b614eee565b81836001600160a01b03166370a08231876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015614c5757600080fd5b505afa158015614c6b573d6000803e3d6000fd5b505050506040513d6020811015614c8157600080fd5b50511015614d0757826001600160a01b03166370a08231866040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015614cd657600080fd5b505afa158015614cea573d6000803e3d6000fd5b505050506040513d6020811015614d0057600080fd5b5051820390505b614e808585856001600160a01b03166370a08231896040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015614d5957600080fd5b505afa158015614d6d573d6000803e3d6000fd5b505050506040513d6020811015614d8357600080fd5b50516040805163313ce56760e01b815290518c916001600160a01b038a169163313ce56791600480820192602092909190829003018186803b158015614dc857600080fd5b505afa158015614ddc573d6000803e3d6000fd5b505050506040513d6020811015614df257600080fd5b5051604080516370a0823160e01b81526001600160a01b038d81166004830152915160ff909316600a0a92918b16916370a0823191602480820192602092909190829003018186803b158015614e4757600080fd5b505afa158015614e5b573d6000803e3d6000fd5b505050506040513d6020811015614e7157600080fd5b505181614e7a57fe5b0461580f565b603654604080516308a8c2c560e31b81526001600160a01b0388811660048301526024820185905291519190921691634546162891604480830192600092919082900301818387803b158015614ed557600080fd5b505af1158015614ee9573d6000803e3d6000fd5b505050505b614fc4565b81836001600160a01b03166370a08231876040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015614f4157600080fd5b505afa158015614f55573d6000803e3d6000fd5b505050506040513d6020811015614f6b57600080fd5b50511015614fb7576040805162461bcd60e51b8152602060048201526014602482015273496e73756666696369656e742042616c616e636560601b604482015290519081900360640190fd5b614fc48585848a8a61580f565b603760009054906101000a90046001600160a01b03166001600160a01b03166387c1678286868a8a6040518563ffffffff1660e01b815260040180856001600160a01b031681526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b83811015615051578181015183820152602001615039565b50505050905090810190601f16801561507e5780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156150b1578181015183820152602001615099565b50505050905090810190601f1680156150de5780820380516001836020036101000a031916815260200191505b509650505050505050600060405180830381600087803b15801561510157600080fd5b505af1158015615115573d6000803e3d6000fd5b5050505050505050505050565b603554604051636e6164d760e01b815260206004820181815288516024840152885160009485946001600160a01b0390911693636e6164d7938c9390928392604490910191908501908083838b5b83811015615188578181015183820152602001615170565b50505050905090810190601f1680156151b55780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156151d257600080fd5b505afa1580156151e6573d6000803e3d6000fd5b505050506040513d60208110156151fc57600080fd5b50516001600160a01b0316148015906152f0575060355460405163383a1caf60e21b81526020600482018181528551602484015285516000946001600160a01b03169363e0e872bc938893928392604401918501908083838b5b8381101561526e578181015183820152602001615256565b50505050905090810190601f16801561529b5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156152b857600080fd5b505afa1580156152cc573d6000803e3d6000fd5b505050506040513d60208110156152e257600080fd5b50516001600160a01b031614155b615331576040805162461bcd60e51b815260206004820152600d60248201526c1b9bdd081cdd5c1c1bdc9d1959609a1b604482015290519081900360640190fd5b60355460405163383a1caf60e21b815260206004820181815285516024840152855160009485946001600160a01b039091169363e0e872bc93899390928392604490910191908501908083838b5b8381101561539757818101518382015260200161537f565b50505050905090810190601f1680156153c45780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156153e157600080fd5b505afa1580156153f5573d6000803e3d6000fd5b505050506040513d602081101561540b57600080fd5b5051603554604051636e6164d760e01b81526020600482018181528c5160248401528c516001600160a01b0390941693636e6164d7938e9383926044909201919085019080838360005b8381101561546d578181015183820152602001615455565b50505050905090810190601f16801561549a5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156154b757600080fd5b505afa1580156154cb573d6000803e3d6000fd5b505050506040513d60208110156154e157600080fd5b50516040805163313ce56760e01b815290519294509092506000916001600160a01b0385169163313ce567916004808301926020929190829003018186803b15801561552c57600080fd5b505afa158015615540573d6000803e3d6000fd5b505050506040513d602081101561555657600080fd5b505160408051636eb1769f60e11b81526001600160a01b038a811660048301528981166024830152915160ff909316600a0a8b02935083929185169163dd62ed3e91604480820192602092909190829003018186803b1580156155b857600080fd5b505afa1580156155cc573d6000803e3d6000fd5b505050506040513d60208110156155e257600080fd5b50511015615627576040805162461bcd60e51b815260206004820152600d60248201526c73657420616c6c6f77616e636560981b604482015290519081900360640190fd5b816001600160a01b03166323b872dd8888846040518463ffffffff1660e01b815260040180846001600160a01b03168152602001836001600160a01b031681526020018281526020019350505050600060405180830381600087803b15801561568f57600080fd5b505af11580156156a3573d6000803e3d6000fd5b50505050603760009054906101000a90046001600160a01b03166001600160a01b03166387c16782888b888c6040518563ffffffff1660e01b815260040180856001600160a01b031681526020018060200180602001848152602001838103835286818151815260200191508051906020019080838360005b8381101561573457818101518382015260200161571c565b50505050905090810190601f1680156157615780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b8381101561579457818101518382015260200161577c565b50505050905090810190601f1680156157c15780820380516001836020036101000a031916815260200191505b509650505050505050600060405180830381600087803b1580156157e457600080fd5b505af11580156157f8573d6000803e3d6000fd5b50929b9a5050505050505050505050565b303b1590565b60355460405163383a1caf60e21b815260206004820181815285516024840152855160009485946001600160a01b039091169363e0e872bc93899390928392604490910191908501908083838b5b8381101561587557818101518382015260200161585d565b50505050905090810190601f1680156158a25780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156158bf57600080fd5b505afa1580156158d3573d6000803e3d6000fd5b505050506040513d60208110156158e957600080fd5b5051603554604051636e6164d760e01b81526020600482018181528a5160248401528a516001600160a01b0390941693636e6164d7938c9383926044909201919085019080838360005b8381101561594b578181015183820152602001615933565b50505050905090810190601f1680156159785780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561599557600080fd5b505afa1580156159a9573d6000803e3d6000fd5b505050506040513d60208110156159bf57600080fd5b505160375460405163e5361ea960e01b81526001600160a01b038b811660048301908152602483018b90526060604484019081528c5160648501528c5196985094965092169363e5361ea9938c938b938d93919291608490910190602085019080838360005b83811015615a3d578181015183820152602001615a25565b50505050905090810190601f168015615a6a5780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b158015615a8b57600080fd5b505af1158015615a9f573d6000803e3d6000fd5b50505050816001600160a01b03166379cc679088876040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015615afa57600080fd5b505af1158015615b0e573d6000803e3d6000fd5b5050603754604080516354cf2aeb60e01b815290516001600160a01b039092169350631a3aba979250879160649185916354cf2aeb91600480820192602092909190829003018186803b158015615b6457600080fd5b505afa158015615b78573d6000803e3d6000fd5b505050506040513d6020811015615b8e57600080fd5b5051890281615b9957fe5b046040518363ffffffff1660e01b81526004018080602001838152602001828103825284818151815260200191508051906020019080838360005b83811015615bec578181015183820152602001615bd4565b50505050905090810190601f168015615c195780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015615c3957600080fd5b505af1158015615c4d573d6000803e3d6000fd5b5050603654604051632a8fa4af60e21b81526001600160a01b038b811660048301908152604483018990526060602484019081528c5160648501528c5192909416955063aa3e92bc94508c938c938a93608490910190602086019080838360005b83811015615cc6578181015183820152602001615cae565b50505050905090810190601f168015615cf35780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b158015615d1457600080fd5b505af1158015615d28573d6000803e3d6000fd5b5050505060006064603760009054906101000a90046001600160a01b03166001600160a01b03166354cf2aeb6040518163ffffffff1660e01b815260040160206040518083038186803b158015615d7e57600080fd5b505afa158015615d92573d6000803e3d6000fd5b505050506040513d6020811015615da857600080fd5b5051870281615db357fe5b0486039050816001600160a01b031663a9059cbb89836040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015615e0f57600080fd5b505af1158015615e23573d6000803e3d6000fd5b505050505050505050505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10615e7257805160ff1916838001178555615e9f565b82800160010185558215615e9f579182015b82811115615e9f578251825591602001919060010190615e84565b50615eab929150615eaf565b5090565b5b80821115615eab5760008155600101615eb056fe436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a6564a26469706673582212202daf5d8b52d17ff7c668eb34e0b3c05e10a9b4d043597948814053c78e9bb42264736f6c634300060c0033
[ 0, 4, 7, 17, 11, 9, 12, 13, 2 ]
0x53d56b4b1EaEd898Be40cF445a715c55dDD6B09C
pragma solidity 0.6.12; 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; } } interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr, bool managedContract); event ManagerChanged(string role, address newManager); event ContractRegistryUpdated(address newContractRegistry); /* * External functions */ /// @dev updates the contracts address and emits a corresponding event /// managedContract indicates whether the contract is managed by the registry and notified on changes function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdmin */; /// @dev returns the current address of the given contracts function getContract(string calldata contractName) external view returns (address); /// @dev returns the list of contract addresses managed by the registry function getManagedContracts() external view returns (address[] memory); function setManager(string calldata role, address manager) external /* onlyAdmin */; function getManager(string calldata role) external view returns (address); function lockContracts() external /* onlyAdmin */; function unlockContracts() external /* onlyAdmin */; function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; function getPreviousContractRegistry() external view returns (address); } interface IDelegations /* is IStakeChangeNotifier */ { // Delegation state change events event DelegatedStakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, address indexed delegator, uint256 delegatorContributedStake); // Function calls event Delegated(address indexed from, address indexed to); /* * External functions */ /// @dev Stake delegation function delegate(address to) external /* onlyWhenActive */; function refreshStake(address addr) external /* onlyWhenActive */; function getDelegatedStake(address addr) external view returns (uint256); function getDelegation(address addr) external view returns (address); function getDelegationInfo(address addr) external view returns (address delegation, uint256 delegatorStake); function getTotalDelegatedStake() external view returns (uint256) ; /* * Governance functions */ event DelegationsImported(address[] from, address indexed to); event DelegationInitialized(address indexed from, address indexed to); function importDelegations(address[] calldata from, address to) external /* onlyMigrationManager onlyDuringDelegationImport */; function initDelegation(address from, address to) external /* onlyInitializationAdmin */; } interface IElections { // Election state change events event StakeChanged(address indexed addr, uint256 selfStake, uint256 delegatedStake, uint256 effectiveStake); event GuardianStatusUpdated(address indexed guardian, bool readyToSync, bool readyForCommittee); // Vote out / Vote unready event GuardianVotedUnready(address indexed guardian); event VoteUnreadyCasted(address indexed voter, address indexed subject, uint256 expiration); event GuardianVotedOut(address indexed guardian); event VoteOutCasted(address indexed voter, address indexed subject); /* * External functions */ /// @dev Called by a guardian when ready to start syncing with other nodes function readyToSync() external; /// @dev Called by a guardian when ready to join the committee, typically after syncing is complete or after being voted out function readyForCommittee() external; /// @dev Called to test if a guardian calling readyForCommittee() will lead to joining the committee function canJoinCommittee(address guardian) external view returns (bool); /// @dev Returns an address effective stake function getEffectiveStake(address guardian) external view returns (uint effectiveStake); /// @dev returns the current committee /// used also by the rewards and fees contracts function getCommittee() external view returns (address[] memory committee, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips); // Vote-unready /// @dev Called by a guardian as part of the automatic vote-unready flow function voteUnready(address subject, uint expiration) external; function getVoteUnreadyVote(address voter, address subject) external view returns (bool valid, uint256 expiration); /// @dev Returns the current vote-unready status of a subject guardian. /// votes indicates wether the specific committee member voted the guardian unready function getVoteUnreadyStatus(address subject) external view returns ( address[] memory committee, uint256[] memory weights, bool[] memory certification, bool[] memory votes, bool subjectInCommittee, bool subjectInCertifiedCommittee ); // Vote-out /// @dev Casts a voteOut vote by the sender to the given address function voteOut(address subject) external; /// @dev Returns the subject address the addr has voted-out against function getVoteOutVote(address voter) external view returns (address); /// @dev Returns the governance voteOut status of a guardian. /// A guardian is voted out if votedStake / totalDelegatedStake (in percent mille) > threshold function getVoteOutStatus(address subject) external view returns (bool votedOut, uint votedStake, uint totalDelegatedStake); /* * Notification functions from other PoS contracts */ /// @dev Called by: delegation contract /// Notifies a delegated stake change event /// total_delegated_stake = 0 if addr delegates to another guardian function delegatedStakeChange(address delegate, uint256 selfStake, uint256 delegatedStake, uint256 totalDelegatedStake) external /* onlyDelegationsContract onlyWhenActive */; /// @dev Called by: guardian registration contract /// Notifies a new guardian was unregistered function guardianUnregistered(address guardian) external /* onlyGuardiansRegistrationContract */; /// @dev Called by: guardian registration contract /// Notifies on a guardian certification change function guardianCertificationChanged(address guardian, bool isCertified) external /* onlyCertificationContract */; /* * Governance functions */ event VoteUnreadyTimeoutSecondsChanged(uint32 newValue, uint32 oldValue); event VoteOutPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue); event VoteUnreadyPercentMilleThresholdChanged(uint32 newValue, uint32 oldValue); event MinSelfStakePercentMilleChanged(uint32 newValue, uint32 oldValue); /// @dev Sets the minimum self-stake required for the effective stake /// minSelfStakePercentMille - the minimum self stake in percent-mille (0-100,000) function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) external /* onlyFunctionalManager onlyWhenActive */; /// @dev Returns the minimum self-stake required for the effective stake function getMinSelfStakePercentMille() external view returns (uint32); /// @dev Sets the vote-out threshold /// voteOutPercentMilleThreshold - the minimum threshold in percent-mille (0-100,000) function setVoteOutPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) external /* onlyFunctionalManager onlyWhenActive */; /// @dev Returns the vote-out threshold function getVoteOutPercentMilleThreshold() external view returns (uint32); /// @dev Sets the vote-unready threshold /// voteUnreadyPercentMilleThreshold - the minimum threshold in percent-mille (0-100,000) function setVoteUnreadyPercentMilleThreshold(uint32 voteUnreadyPercentMilleThreshold) external /* onlyFunctionalManager onlyWhenActive */; /// @dev Returns the vote-unready threshold function getVoteUnreadyPercentMilleThreshold() external view returns (uint32); /// @dev Returns the contract's settings function getSettings() external view returns ( uint32 minSelfStakePercentMille, uint32 voteUnreadyPercentMilleThreshold, uint32 voteOutPercentMilleThreshold ); function initReadyForCommittee(address[] calldata guardians) external /* onlyInitializationAdmin */; } interface ILockable { event Locked(); event Unlocked(); function lock() external /* onlyLockOwner */; function unlock() external /* onlyLockOwner */; function isLocked() view external returns (bool); } interface IStakeChangeNotifier { /// @dev Notifies of stake change event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The difference in the total staked amount. /// @param _sign bool The sign of the added (true) or subtracted (false) amount. /// @param _updatedStake uint256 The updated total staked amount. function stakeChange(address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake) external; /// @dev Notifies of multiple stake change events. /// @param _stakeOwners address[] The addresses of subject stake owners. /// @param _amounts uint256[] The differences in total staked amounts. /// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts. /// @param _updatedStakes uint256[] The updated total staked amounts. function stakeChangeBatch(address[] calldata _stakeOwners, uint256[] calldata _amounts, bool[] calldata _signs, uint256[] calldata _updatedStakes) external; /// @dev Notifies of stake migration event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The migrated amount. function stakeMigration(address _stakeOwner, uint256 _amount) external; } interface IStakingContractHandler { event StakeChangeNotificationSkipped(address indexed stakeOwner); event StakeChangeBatchNotificationSkipped(address[] stakeOwners); event StakeMigrationNotificationSkipped(address indexed stakeOwner); /* * External functions */ /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The total stake. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256); /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256); /* * Governance functions */ event NotifyDelegationsChanged(bool notifyDelegations); function setNotifyDelegations(bool notifyDelegations) external; /* onlyMigrationManager */ function getNotifyDelegations() external returns (bool); } interface IStakingRewards { event DelegatorStakingRewardsAssigned(address indexed delegator, uint256 amount, uint256 totalAwarded, address guardian, uint256 delegatorRewardsPerToken); event GuardianStakingRewardsAssigned(address indexed guardian, uint256 amount, uint256 totalAwarded, uint256 delegatorRewardsPerToken, uint256 stakingRewardsPerWeight); event StakingRewardsClaimed(address indexed addr, uint256 claimedDelegatorRewards, uint256 claimedGuardianRewards, uint256 totalClaimedDelegatorRewards, uint256 totalClaimedGuardianRewards); event StakingRewardsAllocated(uint256 allocatedRewards, uint256 stakingRewardsPerWeight); event GuardianDelegatorsStakingRewardsPercentMilleUpdated(address indexed guardian, uint256 delegatorsStakingRewardsPercentMille); /* * External functions */ /// @dev Returns the currently unclaimed orbs token reward balance of the given address. function getStakingRewardsBalance(address addr) external view returns (uint256 balance); /// @dev Allows Guardian to set a different delegator staking reward cut than the default /// delegatorRewardsPercentMille accepts values between 0 - maxDelegatorsStakingRewardsPercentMille function setGuardianDelegatorsStakingRewardsPercentMille(uint32 delegatorRewardsPercentMille) external; /// @dev Returns the guardian's delegatorRewardsPercentMille function getGuardianDelegatorsStakingRewardsPercentMille(address guardian) external view returns (uint256 delegatorRewardsRatioPercentMille); /// @dev Claims the staking rewards balance of addr by staking function claimStakingRewards(address addr) external; /// @dev Returns the amount of ORBS tokens in the staking wallet that were allocated /// but not yet claimed. The staking wallet balance must always larger than the allocated value. function getStakingRewardsWalletAllocatedTokens() external view returns (uint256 allocated); function getGuardianStakingRewardsData(address guardian) external view returns ( uint256 balance, uint256 claimed, uint256 delegatorRewardsPerToken, uint256 lastStakingRewardsPerWeight ); function getDelegatorStakingRewardsData(address delegator) external view returns ( uint256 balance, uint256 claimed, uint256 lastDelegatorRewardsPerToken ); function getStakingRewardsState() external view returns ( uint96 stakingRewardsPerWeight, uint96 unclaimedStakingRewards ); function getCurrentStakingRewardsRatePercentMille() external returns (uint256); /// @dev called by the Committee contract upon expected change in the committee membership of the guardian /// Triggers update of the member rewards function committeeMembershipWillChange(address guardian, uint256 weight, uint256 totalCommitteeWeight, bool inCommittee, bool inCommitteeAfter) external /* onlyCommitteeContract */; /// @dev called by the Delegation contract upon expected change in a committee member delegator stake /// Triggers update of the delegator and guardian staking rewards function delegationWillChange(address guardian, uint256 delegatedStake, address delegator, uint256 delegatorStake, address nextGuardian, uint256 nextGuardianDelegatedStake) external /* onlyDelegationsContract */; /* * Governance functions */ event AnnualStakingRewardsRateChanged(uint256 annualRateInPercentMille, uint256 annualCap); event DefaultDelegatorsStakingRewardsChanged(uint32 defaultDelegatorsStakingRewardsPercentMille); event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille); event RewardDistributionActivated(uint256 startTime); event RewardDistributionDeactivated(); event StakingRewardsBalanceMigrated(address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards, address toRewardsContract); event StakingRewardsBalanceMigrationAccepted(address from, address indexed addr, uint256 guardianStakingRewards, uint256 delegatorStakingRewards); event EmergencyWithdrawal(address addr); /// @dev activates reward distribution, all rewards will be distributed up /// assuming the last assignment was on startTime (the time the old contarct was deactivated) function activateRewardDistribution(uint startTime) external /* onlyInitializationAdmin */; /// @dev deactivates reward distribution, all rewards will be distributed up /// deactivate moment. function deactivateRewardDistribution() external /* onlyMigrationManager */; /// @dev Sets the default cut of the delegators staking reward. function setDefaultDelegatorsStakingRewardsPercentMille(uint32 defaultDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager onlyWhenActive */; function getDefaultDelegatorsStakingRewardsPercentMille() external view returns (uint32); /// @dev Sets the maximum cut of the delegators staking reward. function setMaxDelegatorsStakingRewardsPercentMille(uint32 maxDelegatorsStakingRewardsPercentMille) external /* onlyFunctionalManager onlyWhenActive */; function getMaxDelegatorsStakingRewardsPercentMille() external view returns (uint32); /// @dev Sets a new annual rate and cap for the staking reward. function setAnnualStakingRewardsRate(uint256 annualRateInPercentMille, uint256 annualCap) external /* onlyFunctionalManager */; function getAnnualStakingRewardsRatePercentMille() external view returns (uint32); function getAnnualStakingRewardsCap() external view returns (uint256); function isRewardAllocationActive() external view returns (bool); /// @dev Returns the contract's settings function getSettings() external view returns ( uint annualStakingRewardsCap, uint32 annualStakingRewardsRatePercentMille, uint32 defaultDelegatorsStakingRewardsPercentMille, uint32 maxDelegatorsStakingRewardsPercentMille, bool rewardAllocationActive ); /// @dev migrates the staking rewards balance of the guardian to the rewards contract as set in the registry. function migrateRewardsBalance(address guardian) external; /// @dev accepts guardian's balance migration from a previous rewards contarct. function acceptRewardsBalanceMigration(address guardian, uint256 guardianStakingRewards, uint256 delegatorStakingRewards) external; /// @dev emergency withdrawal of the rewards contract balances, may eb called only by the EmergencyManager. function emergencyWithdraw() external /* onlyMigrationManager */; } contract Initializable { address private _initializationAdmin; event InitializationComplete(); constructor() public{ _initializationAdmin = msg.sender; } modifier onlyInitializationAdmin() { require(msg.sender == initializationAdmin(), "sender is not the initialization admin"); _; } /* * External functions */ function initializationAdmin() public view returns (address) { return _initializationAdmin; } function initializationComplete() external onlyInitializationAdmin { _initializationAdmin = address(0); emit InitializationComplete(); } function isInitializationComplete() public view returns (bool) { return _initializationAdmin == address(0); } } 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 SafeMath96 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint96 a, uint256 b) internal pure returns (uint96) { require(uint256(uint96(b)) == b, "SafeMath: addition overflow"); uint96 c = a + uint96(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(uint96 a, uint256 b) internal pure returns (uint96) { require(uint256(uint96(b)) == b, "SafeMath: subtraction overflow"); return sub(a, uint96(b), "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); uint96 c = a - b; return c; } } contract WithClaimableRegistryManagement is Context { address private _registryAdmin; address private _pendingRegistryAdmin; event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin); /** * @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin. */ constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); } /** * @dev Returns the address of the current registryAdmin. */ function registryAdmin() public view returns (address) { return _registryAdmin; } /** * @dev Throws if called by any account other than the registryAdmin. */ modifier onlyRegistryAdmin() { require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin"); _; } /** * @dev Returns true if the caller is the current registryAdmin. */ function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; } /** * @dev Leaves the contract without registryAdmin. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current registryAdmin. * * NOTE: Renouncing registryManagement will leave the contract without an registryAdmin, * thereby removing any functionality that is only available to the registryAdmin. */ function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); } /** * @dev Transfers registryManagement of the contract to a new account (`newManager`). */ function _transferRegistryManagement(address newRegistryAdmin) internal { require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address"); emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin); _registryAdmin = newRegistryAdmin; } /** * @dev Modifier throws if called by any account other than the pendingManager. */ modifier onlyPendingRegistryAdmin() { require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin"); _; } /** * @dev Allows the current registryAdmin to set the pendingManager address. * @param newRegistryAdmin The address to transfer registryManagement to. */ function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin { _pendingRegistryAdmin = newRegistryAdmin; } /** * @dev Allows the _pendingRegistryAdmin address to finalize the transfer. */ function claimRegistryManagement() external onlyPendingRegistryAdmin { _transferRegistryManagement(_pendingRegistryAdmin); _pendingRegistryAdmin = address(0); } /** * @dev Returns the current pendingRegistryAdmin */ function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; } } contract ContractRegistryAccessor is WithClaimableRegistryManagement, Initializable { IContractRegistry private contractRegistry; constructor(IContractRegistry _contractRegistry, address _registryAdmin) public { require(address(_contractRegistry) != address(0), "_contractRegistry cannot be 0"); setContractRegistry(_contractRegistry); _transferRegistryManagement(_registryAdmin); } modifier onlyAdmin { require(isAdmin(), "sender is not an admin (registryManger or initializationAdmin)"); _; } function isManager(string memory role) internal view returns (bool) { IContractRegistry _contractRegistry = contractRegistry; return isAdmin() || _contractRegistry != IContractRegistry(0) && contractRegistry.getManager(role) == msg.sender; } function isAdmin() internal view returns (bool) { return msg.sender == registryAdmin() || msg.sender == initializationAdmin() || msg.sender == address(contractRegistry); } function getProtocolContract() internal view returns (address) { return contractRegistry.getContract("protocol"); } function getStakingRewardsContract() internal view returns (address) { return contractRegistry.getContract("stakingRewards"); } function getFeesAndBootstrapRewardsContract() internal view returns (address) { return contractRegistry.getContract("feesAndBootstrapRewards"); } function getCommitteeContract() internal view returns (address) { return contractRegistry.getContract("committee"); } function getElectionsContract() internal view returns (address) { return contractRegistry.getContract("elections"); } function getDelegationsContract() internal view returns (address) { return contractRegistry.getContract("delegations"); } function getGuardiansRegistrationContract() internal view returns (address) { return contractRegistry.getContract("guardiansRegistration"); } function getCertificationContract() internal view returns (address) { return contractRegistry.getContract("certification"); } function getStakingContract() internal view returns (address) { return contractRegistry.getContract("staking"); } function getSubscriptionsContract() internal view returns (address) { return contractRegistry.getContract("subscriptions"); } function getStakingRewardsWallet() internal view returns (address) { return contractRegistry.getContract("stakingRewardsWallet"); } function getBootstrapRewardsWallet() internal view returns (address) { return contractRegistry.getContract("bootstrapRewardsWallet"); } function getGeneralFeesWallet() internal view returns (address) { return contractRegistry.getContract("generalFeesWallet"); } function getCertifiedFeesWallet() internal view returns (address) { return contractRegistry.getContract("certifiedFeesWallet"); } function getStakingContractHandler() internal view returns (address) { return contractRegistry.getContract("stakingContractHandler"); } /* * Governance functions */ event ContractRegistryAddressUpdated(address addr); function setContractRegistry(IContractRegistry newContractRegistry) public onlyAdmin { require(newContractRegistry.getPreviousContractRegistry() == address(contractRegistry), "new contract registry must provide the previous contract registry"); contractRegistry = newContractRegistry; emit ContractRegistryAddressUpdated(address(newContractRegistry)); } function getContractRegistry() public view returns (IContractRegistry) { return contractRegistry; } } contract Lockable is ILockable, ContractRegistryAccessor { bool public locked; constructor(IContractRegistry _contractRegistry, address _registryAdmin) ContractRegistryAccessor(_contractRegistry, _registryAdmin) public {} modifier onlyLockOwner() { require(msg.sender == registryAdmin() || msg.sender == address(getContractRegistry()), "caller is not a lock owner"); _; } function lock() external override onlyLockOwner { locked = true; emit Locked(); } function unlock() external override onlyLockOwner { locked = false; emit Unlocked(); } function isLocked() external override view returns (bool) { return locked; } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } contract ManagedContract is Lockable { constructor(IContractRegistry _contractRegistry, address _registryAdmin) Lockable(_contractRegistry, _registryAdmin) public {} modifier onlyMigrationManager { require(isManager("migrationManager"), "sender is not the migration manager"); _; } modifier onlyFunctionalManager { require(isManager("functionalManager"), "sender is not the functional manager"); _; } function refreshContracts() virtual external {} } contract Delegations is IDelegations, IStakeChangeNotifier, ManagedContract { using SafeMath for uint256; using SafeMath96 for uint96; address constant public VOID_ADDR = address(-1); struct StakeOwnerData { address delegation; uint96 stake; } mapping(address => StakeOwnerData) public stakeOwnersData; mapping(address => uint256) public uncappedDelegatedStake; uint256 totalDelegatedStake; struct DelegateStatus { address addr; uint256 uncappedDelegatedStake; bool isSelfDelegating; uint256 delegatedStake; uint96 selfDelegatedStake; } constructor(IContractRegistry _contractRegistry, address _registryAdmin) ManagedContract(_contractRegistry, _registryAdmin) public { address VOID_ADDRESS_DUMMY_DELEGATION = address(-2); assert(VOID_ADDR != VOID_ADDRESS_DUMMY_DELEGATION && VOID_ADDR != address(0) && VOID_ADDRESS_DUMMY_DELEGATION != address(0)); stakeOwnersData[VOID_ADDR].delegation = VOID_ADDRESS_DUMMY_DELEGATION; } modifier onlyStakingContractHandler() { require(msg.sender == address(stakingContractHandler), "caller is not the staking contract handler"); _; } /* * External functions */ function delegate(address to) external override onlyWhenActive { delegateFrom(msg.sender, to); } function getDelegation(address addr) external override view returns (address) { return getStakeOwnerData(addr).delegation; } function getDelegationInfo(address addr) external override view returns (address delegation, uint256 delegatorStake) { StakeOwnerData memory data = getStakeOwnerData(addr); return (data.delegation, data.stake); } function getDelegatedStake(address addr) external override view returns (uint256) { return getDelegateStatus(addr).delegatedStake; } function getTotalDelegatedStake() external override view returns (uint256) { return totalDelegatedStake; } function refreshStake(address addr) external override onlyWhenActive { _stakeChange(addr, stakingContractHandler.getStakeBalanceOf(addr)); } /* * Notifications from staking contract */ function stakeChange(address _stakeOwner, uint256, bool, uint256 _updatedStake) external override onlyStakingContractHandler onlyWhenActive { _stakeChange(_stakeOwner, _updatedStake); } function stakeChangeBatch(address[] calldata _stakeOwners, uint256[] calldata _amounts, bool[] calldata _signs, uint256[] calldata _updatedStakes) external override onlyStakingContractHandler onlyWhenActive { uint batchLength = _stakeOwners.length; require(batchLength == _amounts.length, "_stakeOwners, _amounts - array length mismatch"); require(batchLength == _signs.length, "_stakeOwners, _signs - array length mismatch"); require(batchLength == _updatedStakes.length, "_stakeOwners, _updatedStakes - array length mismatch"); for (uint i = 0; i < _stakeOwners.length; i++) { _stakeChange(_stakeOwners[i], _updatedStakes[i]); } } function stakeMigration(address _stakeOwner, uint256 _amount) external override onlyStakingContractHandler onlyWhenActive {} /* * Governance functions */ function importDelegations(address[] calldata from, address to) external override onlyInitializationAdmin { require(to != address(0), "to must be a non zero address"); require(from.length > 0, "from array must contain at least one address"); (uint96 stakingRewardsPerWeight, ) = stakingRewardsContract.getStakingRewardsState(); require(stakingRewardsPerWeight == 0, "no rewards may be allocated prior to importing delegations"); uint256 uncappedDelegatedStakeDelta = 0; StakeOwnerData memory data; uint256 newTotalDelegatedStake = totalDelegatedStake; DelegateStatus memory delegateStatus = getDelegateStatus(to); IStakingContractHandler _stakingContractHandler = stakingContractHandler; uint256 delegatorUncapped; uint256[] memory delegatorsStakes = new uint256[](from.length); for (uint i = 0; i < from.length; i++) { data = stakeOwnersData[from[i]]; require(data.delegation == address(0), "import allowed only for uninitialized accounts. existing delegation detected"); require(from[i] != to, "import cannot be used for self-delegation (already self delegated)"); require(data.stake == 0 , "import allowed only for uninitialized accounts. existing stake detected"); // from[i] stops being self delegating. any uncappedDelegatedStake it has now stops being counted towards totalDelegatedStake delegatorUncapped = uncappedDelegatedStake[from[i]]; if (delegatorUncapped > 0) { newTotalDelegatedStake = newTotalDelegatedStake.sub(delegatorUncapped); emit DelegatedStakeChanged( from[i], 0, 0, from[i], 0 ); } // update state data.delegation = to; data.stake = uint96(_stakingContractHandler.getStakeBalanceOf(from[i])); stakeOwnersData[from[i]] = data; uncappedDelegatedStakeDelta = uncappedDelegatedStakeDelta.add(data.stake); // store individual stake for event delegatorsStakes[i] = data.stake; emit Delegated(from[i], to); emit DelegatedStakeChanged( to, delegateStatus.selfDelegatedStake, delegateStatus.isSelfDelegating ? delegateStatus.delegatedStake.add(uncappedDelegatedStakeDelta) : 0, from[i], data.stake ); } // update totals uncappedDelegatedStake[to] = uncappedDelegatedStake[to].add(uncappedDelegatedStakeDelta); if (delegateStatus.isSelfDelegating) { newTotalDelegatedStake = newTotalDelegatedStake.add(uncappedDelegatedStakeDelta); } totalDelegatedStake = newTotalDelegatedStake; // emit events emit DelegationsImported(from, to); } function initDelegation(address from, address to) external override onlyInitializationAdmin { delegateFrom(from, to); emit DelegationInitialized(from, to); } /* * Private functions */ function getDelegateStatus(address addr) private view returns (DelegateStatus memory status) { StakeOwnerData memory data = getStakeOwnerData(addr); status.addr = addr; status.uncappedDelegatedStake = uncappedDelegatedStake[addr]; status.isSelfDelegating = data.delegation == addr; status.selfDelegatedStake = status.isSelfDelegating ? data.stake : 0; status.delegatedStake = status.isSelfDelegating ? status.uncappedDelegatedStake : 0; return status; } function getStakeOwnerData(address addr) private view returns (StakeOwnerData memory data) { data = stakeOwnersData[addr]; data.delegation = (data.delegation == address(0)) ? addr : data.delegation; return data; } struct DelegateFromVars { DelegateStatus prevDelegateStatusBefore; DelegateStatus newDelegateStatusBefore; DelegateStatus prevDelegateStatusAfter; DelegateStatus newDelegateStatusAfter; } function delegateFrom(address from, address to) private { require(to != address(0), "cannot delegate to a zero address"); DelegateFromVars memory vars; StakeOwnerData memory delegatorData = getStakeOwnerData(from); // Optimization - no need for the full flow in the case of a zero staked delegator with no delegations if (delegatorData.stake == 0 && uncappedDelegatedStake[from] == 0) { stakeOwnersData[from].delegation = to; emit Delegated(from, to); return; } address prevDelegate = delegatorData.delegation; vars.prevDelegateStatusBefore = getDelegateStatus(prevDelegate); vars.newDelegateStatusBefore = getDelegateStatus(to); stakingRewardsContract.delegationWillChange(prevDelegate, vars.prevDelegateStatusBefore.delegatedStake, from, delegatorData.stake, to, vars.newDelegateStatusBefore.delegatedStake); stakeOwnersData[from].delegation = to; uint256 delegatorStake = delegatorData.stake; uncappedDelegatedStake[prevDelegate] = vars.prevDelegateStatusBefore.uncappedDelegatedStake.sub(delegatorStake); uncappedDelegatedStake[to] = vars.newDelegateStatusBefore.uncappedDelegatedStake.add(delegatorStake); vars.prevDelegateStatusAfter = getDelegateStatus(prevDelegate); vars.newDelegateStatusAfter = getDelegateStatus(to); uint256 _totalDelegatedStake = totalDelegatedStake.sub( vars.prevDelegateStatusBefore.delegatedStake ).add( vars.prevDelegateStatusAfter.delegatedStake ).sub( vars.newDelegateStatusBefore.delegatedStake ).add( vars.newDelegateStatusAfter.delegatedStake ); totalDelegatedStake = _totalDelegatedStake; emit Delegated(from, to); IElections _electionsContract = electionsContract; if (vars.prevDelegateStatusBefore.delegatedStake != vars.prevDelegateStatusAfter.delegatedStake) { _electionsContract.delegatedStakeChange( prevDelegate, vars.prevDelegateStatusAfter.selfDelegatedStake, vars.prevDelegateStatusAfter.delegatedStake, _totalDelegatedStake ); emit DelegatedStakeChanged( prevDelegate, vars.prevDelegateStatusAfter.selfDelegatedStake, vars.prevDelegateStatusAfter.delegatedStake, from, 0 ); } if (vars.newDelegateStatusBefore.delegatedStake != vars.newDelegateStatusAfter.delegatedStake) { _electionsContract.delegatedStakeChange( to, vars.newDelegateStatusAfter.selfDelegatedStake, vars.newDelegateStatusAfter.delegatedStake, _totalDelegatedStake ); emit DelegatedStakeChanged( to, vars.newDelegateStatusAfter.selfDelegatedStake, vars.newDelegateStatusAfter.delegatedStake, from, delegatorStake ); } } function _stakeChange(address _stakeOwner, uint256 _updatedStake) private { StakeOwnerData memory stakeOwnerDataBefore = getStakeOwnerData(_stakeOwner); DelegateStatus memory delegateStatusBefore = getDelegateStatus(stakeOwnerDataBefore.delegation); uint256 prevUncappedStake = delegateStatusBefore.uncappedDelegatedStake; uint256 newUncappedStake = prevUncappedStake.sub(stakeOwnerDataBefore.stake).add(_updatedStake); stakingRewardsContract.delegationWillChange(stakeOwnerDataBefore.delegation, delegateStatusBefore.delegatedStake, _stakeOwner, stakeOwnerDataBefore.stake, stakeOwnerDataBefore.delegation, delegateStatusBefore.delegatedStake); uncappedDelegatedStake[stakeOwnerDataBefore.delegation] = newUncappedStake; require(uint256(uint96(_updatedStake)) == _updatedStake, "Delegations::updatedStakes value too big (>96 bits)"); stakeOwnersData[_stakeOwner].stake = uint96(_updatedStake); uint256 _totalDelegatedStake = totalDelegatedStake; if (delegateStatusBefore.isSelfDelegating) { _totalDelegatedStake = _totalDelegatedStake.sub(stakeOwnerDataBefore.stake).add(_updatedStake); totalDelegatedStake = _totalDelegatedStake; } DelegateStatus memory delegateStatusAfter = getDelegateStatus(stakeOwnerDataBefore.delegation); electionsContract.delegatedStakeChange( stakeOwnerDataBefore.delegation, delegateStatusAfter.selfDelegatedStake, delegateStatusAfter.delegatedStake, _totalDelegatedStake ); if (_updatedStake != stakeOwnerDataBefore.stake) { emit DelegatedStakeChanged( stakeOwnerDataBefore.delegation, delegateStatusAfter.selfDelegatedStake, delegateStatusAfter.delegatedStake, _stakeOwner, _updatedStake ); } } /* * Contracts topology / registry interface */ IElections electionsContract; IStakingRewards stakingRewardsContract; IStakingContractHandler stakingContractHandler; function refreshContracts() external override { electionsContract = IElections(getElectionsContract()); stakingContractHandler = IStakingContractHandler(getStakingContractHandler()); stakingRewardsContract = IStakingRewards(getStakingRewardsContract()); } }
0x608060405234801561001057600080fd5b50600436106101da5760003560e01c806390ef9d3f11610104578063cf3b670b116100a2578063efb47c7e11610071578063efb47c7e146105cf578063f83d08ba14610648578063fab46d6614610650578063fcd13d6514610699576101da565b8063cf3b670b146105af578063d2523526146105b7578063e4e99222146105bf578063eec0701f146105c7576101da565b8063a69df4b5116100de578063a69df4b51461056b578063acdb8e0414610573578063ce257ab81461057b578063cf309012146105a7576101da565b806390ef9d3f146103a7578063a39539c61461050d578063a4e2d63414610563576101da565b80633dee40571161017c5780635f94cd9c1161014b5780635f94cd9c1461036957806374c16b23146103715780637c47c16d146103795780638faf2f061461039f576101da565b80633dee4057146102e757806348106fe3146103155780635605a4e51461031d5780635c19a95c14610343576101da565b80632987cea0116101b85780632987cea01461026f5780632a1fac72146102955780632b2937681461029d578063333df154146102df576101da565b8063071880e8146101df5780630e3b7c95146102175780631a0b2c4f14610253575b600080fd5b610205600480360360208110156101f557600080fd5b50356001600160a01b03166106bf565b60408051918252519081900360200190f35b6102516004803603608081101561022d57600080fd5b506001600160a01b03813516906020810135906040810135151590606001356106d1565b005b61025b610784565b604080519115158252519081900360200190f35b6102516004803603602081101561028557600080fd5b50356001600160a01b03166107a8565b610251610825565b6102c3600480360360208110156102b357600080fd5b50356001600160a01b03166108cf565b604080516001600160a01b039092168252519081900360200190f35b6102c36108e1565b610251600480360360408110156102fd57600080fd5b506001600160a01b03813581169160200135166108f0565b61025b610995565b6102516004803603602081101561033357600080fd5b50356001600160a01b03166109a5565b6102516004803603602081101561035957600080fd5b50356001600160a01b0316610a9c565b6102c3610b00565b6102c3610b0f565b6102056004803603602081101561038f57600080fd5b50356001600160a01b0316610b1e565b6102c3610b33565b610251600480360360808110156103bd57600080fd5b8101906020810181356401000000008111156103d857600080fd5b8201836020820111156103ea57600080fd5b8035906020019184602083028401116401000000008311171561040c57600080fd5b91939092909160208101903564010000000081111561042a57600080fd5b82018360208201111561043c57600080fd5b8035906020019184602083028401116401000000008311171561045e57600080fd5b91939092909160208101903564010000000081111561047c57600080fd5b82018360208201111561048e57600080fd5b803590602001918460208302840111640100000000831117156104b057600080fd5b9193909290916020810190356401000000008111156104ce57600080fd5b8201836020820111156104e057600080fd5b8035906020019184602083028401116401000000008311171561050257600080fd5b509092509050610b57565b6105336004803603602081101561052357600080fd5b50356001600160a01b0316610d0b565b604080516001600160a01b0390931683526bffffffffffffffffffffffff90911660208301528051918290030190f35b61025b610d4e565b610251610d6f565b610251610e52565b6102516004803603604081101561059157600080fd5b506001600160a01b038135169060200135610ef7565b61025b610f9e565b610205610fbf565b610251610fc5565b6102c361104d565b61025161105c565b610251600480360360408110156105e557600080fd5b81019060208101813564010000000081111561060057600080fd5b82018360208201111561061257600080fd5b8035906020019184602083028401116401000000008311171561063457600080fd5b9193509150356001600160a01b031661111e565b610251611944565b6106766004803603602081101561066657600080fd5b50356001600160a01b0316611a3e565b604080516001600160a01b03909316835260208301919091528051918290030190f35b610251600480360360208110156106af57600080fd5b50356001600160a01b0316611a73565b60056020526000908152604090205481565b6009546001600160a01b0316331461071a5760405162461bcd60e51b815260040180806020018281038252602a815260200180612c4d602a913960400191505060405180910390fd5b60035474010000000000000000000000000000000000000000900460ff16156107745760405162461bcd60e51b8152600401808060200182810382526025815260200180612b046025913960400191505060405180910390fd5b61077e8482611bf3565b50505050565b600080546001600160a01b0316610799611f57565b6001600160a01b031614905090565b6107b0610784565b6107eb5760405162461bcd60e51b8152600401808060200182810382526040815260200180612e006040913960400191505060405180910390fd5b600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b61082d6108e1565b6001600160a01b0316336001600160a01b03161461087c5760405162461bcd60e51b8152600401808060200182810382526026815260200180612bfb6026913960400191505060405180910390fd5b600280547fffffffffffffffffffffffff00000000000000000000000000000000000000001690556040517f2a2b3ea974fb057582c3b210ef8b5f81492d15673f49d4384bfa3b896a964c3c90600090a1565b60006108da82611f5b565b5192915050565b6002546001600160a01b031690565b6108f86108e1565b6001600160a01b0316336001600160a01b0316146109475760405162461bcd60e51b8152600401808060200182810382526026815260200180612bfb6026913960400191505060405180910390fd5b6109518282611fda565b806001600160a01b0316826001600160a01b03167fcf1993798656f790fc10bf446b6c785f2df06395b16dbb876003a2b018a6465860405160405180910390a35050565b6002546001600160a01b03161590565b60035474010000000000000000000000000000000000000000900460ff16156109ff5760405162461bcd60e51b8152600401808060200182810382526025815260200180612b046025913960400191505060405180910390fd5b600954604080517fe9aea8c80000000000000000000000000000000000000000000000000000000081526001600160a01b0380851660048301529151610a99938593169163e9aea8c8916024808301926020929190829003018186803b158015610a6857600080fd5b505afa158015610a7c573d6000803e3d6000fd5b505050506040513d6020811015610a9257600080fd5b5051611bf3565b50565b60035474010000000000000000000000000000000000000000900460ff1615610af65760405162461bcd60e51b8152600401808060200182810382526025815260200180612b046025913960400191505060405180910390fd5b610a993382611fda565b6001546001600160a01b031690565b6000546001600160a01b031690565b6000610b298261257d565b6060015192915050565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81565b6009546001600160a01b03163314610ba05760405162461bcd60e51b815260040180806020018281038252602a815260200180612c4d602a913960400191505060405180910390fd5b60035474010000000000000000000000000000000000000000900460ff1615610bfa5760405162461bcd60e51b8152600401808060200182810382526025815260200180612b046025913960400191505060405180910390fd5b86858114610c395760405162461bcd60e51b815260040180806020018281038252602e815260200180612e40602e913960400191505060405180910390fd5b808414610c775760405162461bcd60e51b815260040180806020018281038252602c815260200180612c21602c913960400191505060405180910390fd5b808214610cb55760405162461bcd60e51b8152600401808060200182810382526034815260200180612c776034913960400191505060405180910390fd5b60005b88811015610cff57610cf78a8a83818110610ccf57fe5b905060200201356001600160a01b0316858584818110610ceb57fe5b90506020020135611bf3565b600101610cb8565b50505050505050505050565b6004602052600090815260409020546001600160a01b038116907401000000000000000000000000000000000000000090046bffffffffffffffffffffffff1682565b60035474010000000000000000000000000000000000000000900460ff1690565b610d77610b0f565b6001600160a01b0316336001600160a01b03161480610dae5750610d9961104d565b6001600160a01b0316336001600160a01b0316145b610dff576040805162461bcd60e51b815260206004820152601a60248201527f63616c6c6572206973206e6f742061206c6f636b206f776e6572000000000000604482015290519081900360640190fd5b600380547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff1690556040517f19aad37188a1d3921e29eb3c66acf43d81975e107cb650d58cca878627955fd690600090a1565b610e5a610784565b610e955760405162461bcd60e51b8152600401808060200182810382526040815260200180612e006040913960400191505060405180910390fd5b600080546040516001600160a01b03909116907f1f5f028be638d6a0e3b8d56fd05b812ce325cc8dc73cdb0e16df94d6b2725c2e908390a3600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b6009546001600160a01b03163314610f405760405162461bcd60e51b815260040180806020018281038252602a815260200180612c4d602a913960400191505060405180910390fd5b60035474010000000000000000000000000000000000000000900460ff1615610f9a5760405162461bcd60e51b8152600401808060200182810382526025815260200180612b046025913960400191505060405180910390fd5b5050565b60035474010000000000000000000000000000000000000000900460ff1681565b60065490565b6001546001600160a01b0316331461100e5760405162461bcd60e51b8152600401808060200182810382526027815260200180612bd46027913960400191505060405180910390fd5b600154611023906001600160a01b031661260f565b600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b6003546001600160a01b031690565b6110646126c7565b600780547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b03929092169190911790556110a4612788565b600980547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b03929092169190911790556110e4612818565b600880547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b6111266108e1565b6001600160a01b0316336001600160a01b0316146111755760405162461bcd60e51b8152600401808060200182810382526026815260200180612bfb6026913960400191505060405180910390fd5b6001600160a01b0381166111d0576040805162461bcd60e51b815260206004820152601d60248201527f746f206d7573742062652061206e6f6e207a65726f2061646472657373000000604482015290519081900360640190fd5b8161120c5760405162461bcd60e51b815260040180806020018281038252602c815260200180612ba8602c913960400191505060405180910390fd5b600854604080517fcfbe49f200000000000000000000000000000000000000000000000000000000815281516000936001600160a01b03169263cfbe49f29260048082019391829003018186803b15801561126657600080fd5b505afa15801561127a573d6000803e3d6000fd5b505050506040513d604081101561129057600080fd5b505190506bffffffffffffffffffffffff8116156112df5760405162461bcd60e51b815260040180806020018281038252603a815260200180612cab603a913960400191505060405180910390fd5b60006112e9612a3d565b6006546112f4612a54565b6112fd8661257d565b6009549091506001600160a01b0316600060608967ffffffffffffffff8111801561132757600080fd5b50604051908082528060200260200182016040528015611351578160200160208202803683370190505b50905060005b8a81101561184e57600460008d8d8481811061136f57fe5b602090810292909201356001600160a01b03908116845283830194909452506040918201600020825180840190935254928316808352740100000000000000000000000000000000000000009093046bffffffffffffffffffffffff169082015297501561140e5760405162461bcd60e51b815260040180806020018281038252604c815260200180612d5f604c913960600191505060405180910390fd5b896001600160a01b03168c8c8381811061142457fe5b905060200201356001600160a01b03166001600160a01b0316141561147a5760405162461bcd60e51b8152600401808060200182810382526042815260200180612ac26042913960600191505060405180910390fd5b60208701516bffffffffffffffffffffffff16156114c95760405162461bcd60e51b8152600401808060200182810382526047815260200180612d186047913960600191505060405180910390fd5b600560008d8d848181106114d957fe5b905060200201356001600160a01b03166001600160a01b03166001600160a01b0316815260200190815260200160002054925060008311156115b55761151f86846128a8565b95508b8b8281811061152d57fe5b905060200201356001600160a01b03166001600160a01b03168c8c8381811061155257fe5b905060200201356001600160a01b03166001600160a01b03167f52db726bc1b1643b24886ed6f0194a41de9abac79d1c12108aca494e5b2bda6b600080600060405180848152602001838152602001828152602001935050505060405180910390a35b6001600160a01b03808b168852841663e9aea8c88d8d848181106115d557fe5b905060200201356001600160a01b03166040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561162257600080fd5b505afa158015611636573d6000803e3d6000fd5b505050506040513d602081101561164c57600080fd5b50516bffffffffffffffffffffffff16602088015286600460008e8e8581811061167257fe5b602090810292909201356001600160a01b0390811684528383019490945250604090910160002083518154948301517fffffffffffffffffffffffff000000000000000000000000000000000000000090951690841617909216740100000000000000000000000000000000000000006bffffffffffffffffffffffff9485160217909155880151611706918a91166128f1565b975086602001516bffffffffffffffffffffffff1682828151811061172757fe5b602002602001018181525050896001600160a01b03168c8c8381811061174957fe5b905060200201356001600160a01b03166001600160a01b03167f4bc154dd35d6a5cb9206482ecb473cdbf2473006d6bce728b9cc0741bcc59ea260405160405180910390a38b8b8281811061179a57fe5b905060200201356001600160a01b03166001600160a01b03168a6001600160a01b03167f52db726bc1b1643b24886ed6f0194a41de9abac79d1c12108aca494e5b2bda6b876080015188604001516117f3576000611802565b6060890151611802908d6128f1565b8b6020015160405180846bffffffffffffffffffffffff168152602001838152602001826bffffffffffffffffffffffff168152602001935050505060405180910390a3600101611357565b506001600160a01b03891660009081526005602052604090205461187290886128f1565b6001600160a01b038a166000908152600560205260409081902091909155840151156118a5576118a285886128f1565b94505b84600681905550886001600160a01b03167f7bedb97dca1b1ff98032eb6dad66e46016096d6341192dc7c3b1be79b0b1a93a8c8c60405180806020018281038252848482818152602001925060200280828437600083820152604051601f9091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169092018290039550909350505050a25050505050505050505050565b61194c610b0f565b6001600160a01b0316336001600160a01b03161480611983575061196e61104d565b6001600160a01b0316336001600160a01b0316145b6119d4576040805162461bcd60e51b815260206004820152601a60248201527f63616c6c6572206973206e6f742061206c6f636b206f776e6572000000000000604482015290519081900360640190fd5b600380547fffffffffffffffffffffff00ffffffffffffffffffffffffffffffffffffffff16740100000000000000000000000000000000000000001790556040517f0f2e5b6c72c6a4491efd919a9f9a409f324ef0708c11ee57d410c2cb06c0992b90600090a1565b600080611a49612a3d565b611a5284611f5b565b80516020909101519093506bffffffffffffffffffffffff16915050915091565b611a7b61294b565b611ab65760405162461bcd60e51b815260040180806020018281038252603e815260200180612b29603e913960400191505060405180910390fd5b600354604080517f078cbb7c00000000000000000000000000000000000000000000000000000000815290516001600160a01b039283169284169163078cbb7c916004808301926020929190829003018186803b158015611b1657600080fd5b505afa158015611b2a573d6000803e3d6000fd5b505050506040513d6020811015611b4057600080fd5b50516001600160a01b031614611b875760405162461bcd60e51b8152600401808060200182810382526041815260200180612b676041913960600191505060405180910390fd5b600380546001600160a01b0383167fffffffffffffffffffffffff0000000000000000000000000000000000000000909116811790915560408051918252517ffea2d033438b968078a6264409d0104b5f3d2ce7b795afc74918e70f3534f22b9181900360200190a150565b611bfb612a3d565b611c0483611f5b565b9050611c0e612a54565b8151611c199061257d565b90506000816020015190506000611c5585611c4f86602001516bffffffffffffffffffffffff16856128a890919063ffffffff16565b906128f1565b600854855160608601516020880151604080517f8a1f3c020000000000000000000000000000000000000000000000000000000081526001600160a01b0394851660048201819052602482018590528d861660448301526bffffffffffffffffffffffff9093166064820152608481019290925260a48201929092529051939450911691638a1f3c029160c48082019260009290919082900301818387803b158015611d0057600080fd5b505af1158015611d14573d6000803e3d6000fd5b505085516001600160a01b0316600090815260056020526040902083905550506bffffffffffffffffffffffff85168514611d805760405162461bcd60e51b8152600401808060200182810382526033815260200180612ce56033913960400191505060405180910390fd5b6001600160a01b03868116600090815260046020526040908190208054909216740100000000000000000000000000000000000000006bffffffffffffffffffffffff891602179091556006549084015115611e0757611dff86611c4f87602001516bffffffffffffffffffffffff16846128a890919063ffffffff16565b600681905590505b611e0f612a54565b8551611e1a9061257d565b600754875160808301516060840151604080517f61885df80000000000000000000000000000000000000000000000000000000081526001600160a01b0394851660048201526bffffffffffffffffffffffff9093166024840152604483019190915260648201879052519394509116916361885df89160848082019260009290919082900301818387803b158015611eb257600080fd5b505af1158015611ec6573d6000803e3d6000fd5b5050505085602001516bffffffffffffffffffffffff168714611f4d5785516080820151606080840151604080516bffffffffffffffffffffffff909416845260208401919091528281018b9052516001600160a01b03808d169416927f52db726bc1b1643b24886ed6f0194a41de9abac79d1c12108aca494e5b2bda6b92908290030190a35b5050505050505050565b3390565b611f63612a3d565b506001600160a01b03818116600090815260046020908152604091829020825180840190935254928316808352740100000000000000000000000000000000000000009093046bffffffffffffffffffffffff16908201529015611fc8578051611fca565b815b6001600160a01b03168152919050565b6001600160a01b03811661201f5760405162461bcd60e51b8152600401808060200182810382526021815260200180612ddf6021913960400191505060405180910390fd5b612027612a82565b61202f612a3d565b61203884611f5b565b905080602001516bffffffffffffffffffffffff16600014801561207257506001600160a01b038416600090815260056020526040902054155b156120e9576001600160a01b0384811660008181526004602052604080822080547fffffffffffffffffffffffff0000000000000000000000000000000000000000169488169485179055517f4bc154dd35d6a5cb9206482ecb473cdbf2473006d6bce728b9cc0741bcc59ea29190a35050610f9a565b80516120f48161257d565b83526120ff8461257d565b6020808501829052600854855160609081015192860151930151604080517f8a1f3c020000000000000000000000000000000000000000000000000000000081526001600160a01b03878116600483015260248201959095528a851660448201526bffffffffffffffffffffffff9095166064860152888416608486015260a485019190915251911691638a1f3c029160c480830192600092919082900301818387803b1580156121af57600080fd5b505af11580156121c3573d6000803e3d6000fd5b505050506001600160a01b03858116600090815260046020908152604090912080547fffffffffffffffffffffffff00000000000000000000000000000000000000001692871692909217909155828101518451909101516bffffffffffffffffffffffff9091169061223690826128a8565b6001600160a01b03831660009081526005602090815260409091209190915584810151015161226590826128f1565b6001600160a01b0386166000908152600560205260409020556122878261257d565b60408501526122958561257d565b846060018190525060006122e6856060015160600151611c4f8760200151606001516122e0896040015160600151611c4f8b60000151606001516006546128a890919063ffffffff16565b906128a8565b60068190556040519091506001600160a01b0380881691908916907f4bc154dd35d6a5cb9206482ecb473cdbf2473006d6bce728b9cc0741bcc59ea290600090a360075460408601516060908101518751909101516001600160a01b03909216911461245457806001600160a01b03166361885df885886040015160800151896040015160600151866040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846bffffffffffffffffffffffff168152602001838152602001828152602001945050505050600060405180830381600087803b1580156123d157600080fd5b505af11580156123e5573d6000803e3d6000fd5b505050604080880151608081015160609182015183516bffffffffffffffffffffffff9092168252602082015260008184015291516001600160a01b03808d1694508816927f52db726bc1b1643b24886ed6f0194a41de9abac79d1c12108aca494e5b2bda6b92908290030190a35b85606001516060015186602001516060015114611f4d57806001600160a01b03166361885df888886060015160800151896060015160600151866040518563ffffffff1660e01b815260040180856001600160a01b03168152602001846bffffffffffffffffffffffff168152602001838152602001828152602001945050505050600060405180830381600087803b1580156124f057600080fd5b505af1158015612504573d6000803e3d6000fd5b505050606080880151608081015190820151604080516bffffffffffffffffffffffff90931683526020830191909152818101879052516001600160a01b03808d1694508b16927f52db726bc1b1643b24886ed6f0194a41de9abac79d1c12108aca494e5b2bda6b928290030190a35050505050505050565b612585612a54565b61258d612a3d565b61259683611f5b565b6001600160a01b0380851680855260008181526005602090815260409182902054908701528351909216149084018190529091506125d55760006125db565b80602001515b6bffffffffffffffffffffffff16608083015260408201516125fe576000612604565b81602001515b606083015250919050565b6001600160a01b0381166126545760405162461bcd60e51b8152600401808060200182810382526034815260200180612dab6034913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f1f5f028be638d6a0e3b8d56fd05b812ce325cc8dc73cdb0e16df94d6b2725c2e91a3600080547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b600354604080517f35817773000000000000000000000000000000000000000000000000000000008152602060048201819052600960248301527f656c656374696f6e730000000000000000000000000000000000000000000000604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b15801561275757600080fd5b505afa15801561276b573d6000803e3d6000fd5b505050506040513d602081101561278157600080fd5b5051905090565b600354604080517f35817773000000000000000000000000000000000000000000000000000000008152602060048201819052601660248301527f7374616b696e67436f6e747261637448616e646c657200000000000000000000604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b15801561275757600080fd5b600354604080517f35817773000000000000000000000000000000000000000000000000000000008152602060048201819052600e60248301527f7374616b696e6752657761726473000000000000000000000000000000000000604483015291516000936001600160a01b03169263358177739260648082019391829003018186803b15801561275757600080fd5b60006128ea83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506129a6565b9392505050565b6000828201838110156128ea576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6000612955610b0f565b6001600160a01b0316336001600160a01b0316148061298c57506129776108e1565b6001600160a01b0316336001600160a01b0316145b806129a157506003546001600160a01b031633145b905090565b60008184841115612a355760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156129fa5781810151838201526020016129e2565b50505050905090810190601f168015612a275780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b604080518082019091526000808252602082015290565b6040805160a08101825260008082526020820181905291810182905260608101829052608081019190915290565b6040518060800160405280612a95612a54565b8152602001612aa2612a54565b8152602001612aaf612a54565b8152602001612abc612a54565b90529056fe696d706f72742063616e6e6f74206265207573656420666f722073656c662d64656c65676174696f6e2028616c72656164792073656c662064656c65676174656429636f6e7472616374206973206c6f636b656420666f722074686973206f7065726174696f6e73656e646572206973206e6f7420616e2061646d696e202872656769737472794d616e676572206f7220696e697469616c697a6174696f6e41646d696e296e657720636f6e7472616374207265676973747279206d7573742070726f76696465207468652070726576696f757320636f6e747261637420726567697374727966726f6d206172726179206d75737420636f6e7461696e206174206c65617374206f6e65206164647265737343616c6c6572206973206e6f74207468652070656e64696e6720726567697374727941646d696e73656e646572206973206e6f742074686520696e697469616c697a6174696f6e2061646d696e5f7374616b654f776e6572732c205f7369676e73202d206172726179206c656e677468206d69736d6174636863616c6c6572206973206e6f7420746865207374616b696e6720636f6e74726163742068616e646c65725f7374616b654f776e6572732c205f757064617465645374616b6573202d206172726179206c656e677468206d69736d617463686e6f2072657761726473206d617920626520616c6c6f6361746564207072696f7220746f20696d706f7274696e672064656c65676174696f6e7344656c65676174696f6e733a3a757064617465645374616b65732076616c756520746f6f2062696720283e3936206269747329696d706f727420616c6c6f776564206f6e6c7920666f7220756e696e697469616c697a6564206163636f756e74732e206578697374696e67207374616b65206465746563746564696d706f727420616c6c6f776564206f6e6c7920666f7220756e696e697469616c697a6564206163636f756e74732e206578697374696e672064656c65676174696f6e206465746563746564526567697374727941646d696e3a206e657720726567697374727941646d696e20697320746865207a65726f206164647265737363616e6e6f742064656c656761746520746f2061207a65726f206164647265737357697468436c61696d61626c6552656769737472794d616e6167656d656e743a2063616c6c6572206973206e6f742074686520726567697374727941646d696e5f7374616b654f776e6572732c205f616d6f756e7473202d206172726179206c656e677468206d69736d61746368a26469706673582212202c72dab014c8836e4243f4cf10f458ea2feb31c4f06ed854f27f2de6571d432e64736f6c634300060c0033
[ 7, 12 ]
0x5454223e3078Db87e55a15bE541cc925f3702eB0
pragma solidity 0.6.12; 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; } } interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr, bool managedContract); event ManagerChanged(string role, address newManager); event ContractRegistryUpdated(address newContractRegistry); /* * External functions */ /// @dev updates the contracts address and emits a corresponding event /// managedContract indicates whether the contract is managed by the registry and notified on changes function setContract(string calldata contractName, address addr, bool managedContract) external /* onlyAdmin */; /// @dev returns the current address of the given contracts function getContract(string calldata contractName) external view returns (address); /// @dev returns the list of contract addresses managed by the registry function getManagedContracts() external view returns (address[] memory); function setManager(string calldata role, address manager) external /* onlyAdmin */; function getManager(string calldata role) external view returns (address); function lockContracts() external /* onlyAdmin */; function unlockContracts() external /* onlyAdmin */; function setNewContractRegistry(IContractRegistry newRegistry) external /* onlyAdmin */; function getPreviousContractRegistry() external view returns (address); } interface IContractRegistryListener { function refreshContracts() external; function setContractRegistry(IContractRegistry newRegistry) external; } interface ILockable { event Locked(); event Unlocked(); function lock() external /* onlyLockOwner */; function unlock() external /* onlyLockOwner */; function isLocked() view external returns (bool); } contract Initializable { address private _initializationAdmin; event InitializationComplete(); constructor() public{ _initializationAdmin = msg.sender; } modifier onlyInitializationAdmin() { require(msg.sender == initializationAdmin(), "sender is not the initialization admin"); _; } /* * External functions */ function initializationAdmin() public view returns (address) { return _initializationAdmin; } function initializationComplete() external onlyInitializationAdmin { _initializationAdmin = address(0); emit InitializationComplete(); } function isInitializationComplete() public view returns (bool) { return _initializationAdmin == address(0); } } contract WithClaimableRegistryManagement is Context { address private _registryAdmin; address private _pendingRegistryAdmin; event RegistryManagementTransferred(address indexed previousRegistryAdmin, address indexed newRegistryAdmin); /** * @dev Initializes the contract setting the deployer as the initial registryRegistryAdmin. */ constructor () internal { address msgSender = _msgSender(); _registryAdmin = msgSender; emit RegistryManagementTransferred(address(0), msgSender); } /** * @dev Returns the address of the current registryAdmin. */ function registryAdmin() public view returns (address) { return _registryAdmin; } /** * @dev Throws if called by any account other than the registryAdmin. */ modifier onlyRegistryAdmin() { require(isRegistryAdmin(), "WithClaimableRegistryManagement: caller is not the registryAdmin"); _; } /** * @dev Returns true if the caller is the current registryAdmin. */ function isRegistryAdmin() public view returns (bool) { return _msgSender() == _registryAdmin; } /** * @dev Leaves the contract without registryAdmin. It will not be possible to call * `onlyManager` functions anymore. Can only be called by the current registryAdmin. * * NOTE: Renouncing registryManagement will leave the contract without an registryAdmin, * thereby removing any functionality that is only available to the registryAdmin. */ function renounceRegistryManagement() public onlyRegistryAdmin { emit RegistryManagementTransferred(_registryAdmin, address(0)); _registryAdmin = address(0); } /** * @dev Transfers registryManagement of the contract to a new account (`newManager`). */ function _transferRegistryManagement(address newRegistryAdmin) internal { require(newRegistryAdmin != address(0), "RegistryAdmin: new registryAdmin is the zero address"); emit RegistryManagementTransferred(_registryAdmin, newRegistryAdmin); _registryAdmin = newRegistryAdmin; } /** * @dev Modifier throws if called by any account other than the pendingManager. */ modifier onlyPendingRegistryAdmin() { require(msg.sender == _pendingRegistryAdmin, "Caller is not the pending registryAdmin"); _; } /** * @dev Allows the current registryAdmin to set the pendingManager address. * @param newRegistryAdmin The address to transfer registryManagement to. */ function transferRegistryManagement(address newRegistryAdmin) public onlyRegistryAdmin { _pendingRegistryAdmin = newRegistryAdmin; } /** * @dev Allows the _pendingRegistryAdmin address to finalize the transfer. */ function claimRegistryManagement() external onlyPendingRegistryAdmin { _transferRegistryManagement(_pendingRegistryAdmin); _pendingRegistryAdmin = address(0); } /** * @dev Returns the current pendingRegistryAdmin */ function pendingRegistryAdmin() public view returns (address) { return _pendingRegistryAdmin; } } contract ContractRegistry is IContractRegistry, Initializable, WithClaimableRegistryManagement { address previousContractRegistry; mapping(string => address) contracts; address[] managedContractAddresses; mapping(string => address) managers; constructor(address _previousContractRegistry, address registryAdmin) public { previousContractRegistry = _previousContractRegistry; _transferRegistryManagement(registryAdmin); } modifier onlyAdmin { require(msg.sender == registryAdmin() || msg.sender == initializationAdmin(), "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress)"); _; } modifier onlyAdminOrMigrationManager { require(msg.sender == registryAdmin() || msg.sender == initializationAdmin() || msg.sender == managers["migrationManager"], "sender is not an admin (registryAdmin or initializationAdmin when initialization in progress) and not the migration manager"); _; } /* * External functions */ function setContract(string calldata contractName, address addr, bool managedContract) external override onlyAdminOrMigrationManager { require(!managedContract || addr != address(0), "managed contract may not have address(0)"); removeManagedContract(contracts[contractName]); contracts[contractName] = addr; if (managedContract) { addManagedContract(addr); } emit ContractAddressUpdated(contractName, addr, managedContract); notifyOnContractsChange(); } function getContract(string calldata contractName) external override view returns (address) { return contracts[contractName]; } function lockContracts() external override onlyAdminOrMigrationManager { for (uint i = 0; i < managedContractAddresses.length; i++) { ILockable(managedContractAddresses[i]).lock(); } } function unlockContracts() external override onlyAdminOrMigrationManager { for (uint i = 0; i < managedContractAddresses.length; i++) { ILockable(managedContractAddresses[i]).unlock(); } } function getManagedContracts() external override view returns (address[] memory) { return managedContractAddresses; } function setManager(string calldata role, address manager) external override onlyAdmin { managers[role] = manager; emit ManagerChanged(role, manager); } function getManager(string calldata role) external override view returns (address) { return managers[role]; } function setNewContractRegistry(IContractRegistry newRegistry) external override onlyAdmin { for (uint i = 0; i < managedContractAddresses.length; i++) { IContractRegistryListener(managedContractAddresses[i]).setContractRegistry(newRegistry); IContractRegistryListener(managedContractAddresses[i]).refreshContracts(); } emit ContractRegistryUpdated(address(newRegistry)); } function getPreviousContractRegistry() external override view returns (address) { return previousContractRegistry; } /* * Private methods */ function notifyOnContractsChange() private { for (uint i = 0; i < managedContractAddresses.length; i++) { IContractRegistryListener(managedContractAddresses[i]).refreshContracts(); } } function addManagedContract(address addr) private { managedContractAddresses.push(addr); } function removeManagedContract(address addr) private { uint length = managedContractAddresses.length; for (uint i = 0; i < length; i++) { if (managedContractAddresses[i] == addr) { if (i != length - 1) { managedContractAddresses[i] = managedContractAddresses[length-1]; } managedContractAddresses.pop(); length--; } } } }
0x608060405234801561001057600080fd5b50600436106101365760003560e01c806348106fe3116100b257806374c16b2311610081578063acdb8e0411610066578063acdb8e04146103ba578063d0d58748146103c2578063d25235261461043b57610136565b806374c16b231461035a578063854799161461036257610136565b806348106fe31461031c5780635f94cd9c146103245780636ffc1e681461032c5780637225a4bc1461033457610136565b80632a1fac7211610109578063333df154116100ee578063333df15414610223578063358177731461022b57806337b6da131461029b57610136565b80632a1fac72146102135780632e40173c1461021b57610136565b8063078cbb7c1461013b5780631a0b2c4f1461015f5780631ee441e91461017b5780632987cea0146101eb575b600080fd5b610143610443565b604080516001600160a01b039092168252519081900360200190f35b610167610452565b604080519115158252519081900360200190f35b6101436004803603602081101561019157600080fd5b8101906020810181356401000000008111156101ac57600080fd5b8201836020820111156101be57600080fd5b803590602001918460018302840111640100000000831117156101e057600080fd5b509092509050610478565b6102116004803603602081101561020157600080fd5b50356001600160a01b03166104b2565b005b610211610549565b61021161060b565b61014361078f565b6101436004803603602081101561024157600080fd5b81019060208101813564010000000081111561025c57600080fd5b82018360208201111561026e57600080fd5b8035906020019184600183028401116401000000008311171561029057600080fd5b50909250905061079e565b610211600480360360608110156102b157600080fd5b8101906020810181356401000000008111156102cc57600080fd5b8201836020820111156102de57600080fd5b8035906020019184600183028401116401000000008311171561030057600080fd5b91935091506001600160a01b03813516906020013515156107d8565b610167610a74565b610143610a84565b610211610a93565b6102116004803603602081101561034a57600080fd5b50356001600160a01b0316610c14565b610143610e17565b61036a610e26565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156103a657818101518382015260200161038e565b505050509050019250505060405180910390f35b610211610e88565b610211600480360360408110156103d857600080fd5b8101906020810181356401000000008111156103f357600080fd5b82018360208201111561040557600080fd5b8035906020019184600183028401116401000000008311171561042757600080fd5b9193509150356001600160a01b0316610f47565b6102116110bf565b6003546001600160a01b031690565b6001546000906001600160a01b0316610469611161565b6001600160a01b031614905090565b6000600683836040518083838082843791909101948552505060405192839003602001909220546001600160a01b03169250505092915050565b6104ba610452565b61050f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260408152602001806115eb6040913960400191505060405180910390fd5b600280547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b61055161078f565b6001600160a01b0316336001600160a01b0316146105ba576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001806115916026913960400191505060405180910390fd5b600080547fffffffffffffffffffffffff00000000000000000000000000000000000000001681556040517f2a2b3ea974fb057582c3b210ef8b5f81492d15673f49d4384bfa3b896a964c3c9190a1565b610613610e17565b6001600160a01b0316336001600160a01b0316148061064a575061063561078f565b6001600160a01b0316336001600160a01b0316145b806106985750604080517f6d6967726174696f6e4d616e6167657200000000000000000000000000000000815260066010820152905190819003603001902054336001600160a01b03909116145b6106ed576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252607b8152602001806114b9607b913960800191505060405180910390fd5b60005b60055481101561078c576005818154811061070757fe5b6000918252602082200154604080517ff83d08ba00000000000000000000000000000000000000000000000000000000815290516001600160a01b039092169263f83d08ba9260048084019382900301818387803b15801561076857600080fd5b505af115801561077c573d6000803e3d6000fd5b5050600190920191506106f09050565b50565b6000546001600160a01b031690565b6000600483836040518083838082843791909101948552505060405192839003602001909220546001600160a01b03169250505092915050565b6107e0610e17565b6001600160a01b0316336001600160a01b03161480610817575061080261078f565b6001600160a01b0316336001600160a01b0316145b806108655750604080517f6d6967726174696f6e4d616e6167657200000000000000000000000000000000815260066010820152905190819003603001902054336001600160a01b03909116145b6108ba576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252607b8152602001806114b9607b913960800191505060405180910390fd5b8015806108cf57506001600160a01b03821615155b610924576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602881526020018061146a6028913960400191505060405180910390fd5b61095e600485856040518083838082843791909101948552505060405192839003602001909220546001600160a01b031691506111659050565b8160048585604051808383808284379190910194855250506040519283900360200190922080546001600160a01b03949094167fffffffffffffffffffffffff000000000000000000000000000000000000000090941693909317909255505080156109cd576109cd8261128d565b7faf299646760f6fbf25862e53df5b06cf99239f0ae9cfca9ed96d7b459affff20848484846040518080602001846001600160a01b0316815260200183151581526020018281038252868682818152602001925080828437600083820152604051601f9091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690920182900397509095505050505050a1610a6e6112f7565b50505050565b6000546001600160a01b03161590565b6002546001600160a01b031690565b610a9b610e17565b6001600160a01b0316336001600160a01b03161480610ad25750610abd61078f565b6001600160a01b0316336001600160a01b0316145b80610b205750604080517f6d6967726174696f6e4d616e6167657200000000000000000000000000000000815260066010820152905190819003603001902054336001600160a01b03909116145b610b75576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252607b8152602001806114b9607b913960800191505060405180910390fd5b60005b60055481101561078c5760058181548110610b8f57fe5b6000918252602082200154604080517fa69df4b500000000000000000000000000000000000000000000000000000000815290516001600160a01b039092169263a69df4b59260048084019382900301818387803b158015610bf057600080fd5b505af1158015610c04573d6000803e3d6000fd5b505060019092019150610b789050565b610c1c610e17565b6001600160a01b0316336001600160a01b03161480610c535750610c3e61078f565b6001600160a01b0316336001600160a01b0316145b610ca8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252605d815260200180611534605d913960600191505060405180910390fd5b60005b600554811015610dd75760058181548110610cc257fe5b6000918252602082200154604080517ffcd13d650000000000000000000000000000000000000000000000000000000081526001600160a01b0386811660048301529151919092169263fcd13d65926024808201939182900301818387803b158015610d2d57600080fd5b505af1158015610d41573d6000803e3d6000fd5b5050505060058181548110610d5257fe5b6000918252602082200154604080517feec0701f00000000000000000000000000000000000000000000000000000000815290516001600160a01b039092169263eec0701f9260048084019382900301818387803b158015610db357600080fd5b505af1158015610dc7573d6000803e3d6000fd5b505060019092019150610cab9050565b50604080516001600160a01b038316815290517fb3a6e7c81ebdb0cf9bf28d5ddf6678ded8d73b44f2eee06ca3974dbb9f41ce7e9181900360200190a150565b6001546001600160a01b031690565b60606005805480602002602001604051908101604052809291908181526020018280548015610e7e57602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610e60575b5050505050905090565b610e90610452565b610ee5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260408152602001806115eb6040913960400191505060405180910390fd5b6001546040516000916001600160a01b0316907f1f5f028be638d6a0e3b8d56fd05b812ce325cc8dc73cdb0e16df94d6b2725c2e908390a3600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b610f4f610e17565b6001600160a01b0316336001600160a01b03161480610f865750610f7161078f565b6001600160a01b0316336001600160a01b0316145b610fdb576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252605d815260200180611534605d913960600191505060405180910390fd5b806006848460405180838380828437919091019485525050604080516020948190038501812080547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0397881617905594861693850193909352505080825281018390527f325468706c8d44b035396cba93fd6c8dabe53c1f8b51dd2634c62ebe9ddb0de9908490849084908060608101858580828437600083820152604051601f9091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016909201829003965090945050505050a1505050565b6002546001600160a01b03163314611122576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260278152602001806114926027913960400191505060405180910390fd5b600254611137906001600160a01b0316611396565b600280547fffffffffffffffffffffffff0000000000000000000000000000000000000000169055565b3390565b60055460005b8181101561128857826001600160a01b03166005828154811061118a57fe5b6000918252602090912001546001600160a01b031614156112805760018203811461121457600560018303815481106111bf57fe5b600091825260209091200154600580546001600160a01b0390921691839081106111e557fe5b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b031602179055505b600580548061121f57fe5b60008281526020902081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff90810180547fffffffffffffffffffffffff000000000000000000000000000000000000000016905590810190915591909101905b60010161116b565b505050565b600580546001810182556000919091527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db00180547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b60005b60055481101561078c576005818154811061131157fe5b6000918252602082200154604080517feec0701f00000000000000000000000000000000000000000000000000000000815290516001600160a01b039092169263eec0701f9260048084019382900301818387803b15801561137257600080fd5b505af1158015611386573d6000803e3d6000fd5b5050600190920191506112fa9050565b6001600160a01b0381166113f5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260348152602001806115b76034913960400191505060405180910390fd5b6001546040516001600160a01b038084169216907f1f5f028be638d6a0e3b8d56fd05b812ce325cc8dc73cdb0e16df94d6b2725c2e90600090a3600180547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b039290921691909117905556fe6d616e6167656420636f6e7472616374206d6179206e6f742068617665206164647265737328302943616c6c6572206973206e6f74207468652070656e64696e6720726567697374727941646d696e73656e646572206973206e6f7420616e2061646d696e2028726567697374727941646d696e206f7220696e697469616c697a6174696f6e41646d696e207768656e20696e697469616c697a6174696f6e20696e2070726f67726573732920616e64206e6f7420746865206d6967726174696f6e206d616e6167657273656e646572206973206e6f7420616e2061646d696e2028726567697374727941646d696e206f7220696e697469616c697a6174696f6e41646d696e207768656e20696e697469616c697a6174696f6e20696e2070726f67726573732973656e646572206973206e6f742074686520696e697469616c697a6174696f6e2061646d696e526567697374727941646d696e3a206e657720726567697374727941646d696e20697320746865207a65726f206164647265737357697468436c61696d61626c6552656769737472794d616e6167656d656e743a2063616c6c6572206973206e6f742074686520726567697374727941646d696ea26469706673582212209e9967955b9a72addbec1e5e401351068b4de5d7799f3a840f1389c94532457f64736f6c634300060c0033
[ 38 ]
0x54be8f918a89571158d90468d8097bcaa1ce7ca1
pragma solidity 0.6.12; 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 Modifier to use in the initializer function of a contract when upgrade EVEN times. */ modifier initializerEven() { require(initializing || isConstructor() || initialized, "Contract instance has already been initialized EVEN times"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = false; } _; 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 Governable is Initializable { address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function initialize(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } modifier governance() { require(msg.sender == governor); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } contract Configurable is Governable { mapping (bytes32 => uint) internal config; function getConfig(bytes32 key) public view returns (uint) { return config[key]; } function getConfig(bytes32 key, uint index) public view returns (uint) { return config[bytes32(uint(key) ^ index)]; } function getConfig(bytes32 key, address addr) public view returns (uint) { return config[bytes32(uint(key) ^ uint(addr))]; } function _setConfig(bytes32 key, uint value) internal { if(config[key] != value) config[key] = value; } function _setConfig(bytes32 key, uint index, uint value) internal { _setConfig(bytes32(uint(key) ^ index), value); } function _setConfig(bytes32 key, address addr, uint value) internal { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } function setConfig(bytes32 key, uint value) external governance { _setConfig(key, value); } function setConfig(bytes32 key, uint index, uint value) external governance { _setConfig(bytes32(uint(key) ^ index), value); } function setConfig(bytes32 key, address addr, uint value) external governance { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } } interface Minter { event Minted(address indexed recipient, address reward_contract, uint minted); function token() external view returns (address); function controller() external view returns (address); function minted(address, address) external view returns (uint); function allowed_to_mint_for(address, address) external view returns (bool); function mint(address gauge) external; function mint_many(address[8] calldata gauges) external; function mint_for(address gauge, address _for) external; function toggle_approve_mint(address minting_user) external; } interface LiquidityGauge { event Deposit(address indexed provider, uint value); event Withdraw(address indexed provider, uint value); event UpdateLiquidityLimit(address user, uint original_balance, uint original_supply, uint working_balance, uint working_supply); function user_checkpoint (address addr) external returns (bool); function claimable_tokens(address addr) external view returns (uint); function claimable_reward(address addr) external view returns (uint); function integrate_checkpoint() external view returns (uint); function kick(address addr) external; function set_approve_deposit(address addr, bool can_deposit) external; function deposit(uint _value) external; function deposit(uint _value, address addr) external; function withdraw(uint _value) external; function withdraw(uint _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function minter() external view returns (address); function crv_token() external view returns (address); function lp_token() external view returns (address); function controller() external view returns (address); function voting_escrow() external view returns (address); function balanceOf(address) external view returns (uint); function totalSupply() external view returns (uint); function future_epoch_time() external view returns (uint); function approved_to_deposit(address, address) external view returns (bool); function working_balances(address) external view returns (uint); function working_supply() external view returns (uint); function period() external view returns (int128); function period_timestamp(uint) external view returns (uint); function integrate_inv_supply(uint) external view returns (uint); function integrate_inv_supply_of(address) external view returns (uint); function integrate_checkpoint_of(address) external view returns (uint); function integrate_fraction(address) external view returns (uint); function inflation_rate() external view returns (uint); function reward_contract() external view returns (address); function rewarded_token() external view returns (address); function reward_integral() external view returns (uint); function reward_integral_for(address) external view returns (uint); function rewards_for(address) external view returns (uint); function claimed_rewards_for(address) external view returns (uint); } contract SSimpleGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; uint override public reward_integral; mapping(address => uint) override public reward_integral_for; mapping(address => uint) override public rewards_for; mapping(address => uint) override public claimed_rewards_for; uint public span; uint public end; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[addr] = balanceOf[addr].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(addr, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool claim_rewards) virtual override public { _checkpoint(msg.sender, claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address) virtual override public view returns (uint) { return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = SMinter(minter).quotas(address(this)); amount = amount.mul(balanceOf[addr]).div(totalSupply); uint lasttime = integrate_checkpoint_of[addr]; if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); address teamAddr = address(config['teamAddr']); uint teamRatio = config['teamRatio']; if(teamAddr != address(0) && teamRatio != 0) integrate_fraction[teamAddr] = integrate_fraction[teamAddr].add(amount.mul(teamRatio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { uint amount = claimable_tokens(addr); _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); integrate_checkpoint_of[addr] = now; } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return now; } } c SExactGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; bytes32 internal constant _devAddr_ = 'devAddr'; bytes32 internal constant _devRatio_ = 'devRatio'; bytes32 internal constant _ecoAddr_ = 'ecoAddr'; bytes32 internal constant _ecoRatio_ = 'ecoRatio'; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; mapping(address => uint) public reward_integral_; // rewarded_token => reward_integral mapping(address => mapping(address => uint)) public reward_integral_for_; // recipient => rewarded_token => reward_integral_for mapping(address => mapping(address => uint)) public rewards_for_; mapping(address => mapping(address => uint)) public claimed_rewards_for_; uint public span; uint public end; mapping(address => uint) public sumMiningPerOf; uint public sumMiningPer; uint public bufReward; uint public lasttime; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; lasttime = now; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(msg.sender, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool _claim_rewards) virtual override public { _checkpoint(msg.sender, _claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address addr) virtual override public view returns (uint) { addr; return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint) { return _claimable_tokens(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr]); } function _claimable_tokens(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = sumPer.sub(lastSumPer); amount = amount.add(delta.mul(1 ether).div(totalSupply)); amount = amount.mul(balanceOf[addr]).div(1 ether); } function claimableDelta() virtual internal view returns(uint amount) { amount = SMinter(minter).quotas(address(this)).sub(bufReward); if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); addr = address(config[_devAddr_]); uint ratio = config[_devRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); addr = address(config[_ecoAddr_]); ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { if(span == 0 || totalSupply == 0) return; uint delta = claimableDelta(); uint amount = _claimable_tokens(addr, delta, sumMiningPer, sumMiningPerOf[addr]); if(delta != amount) bufReward = bufReward.add(delta).sub(amount); if(delta > 0) sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(totalSupply)); if(sumMiningPerOf[addr] != sumMiningPer) sumMiningPerOf[addr] = sumMiningPer; lasttime = now; _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return lasttime; } function reward_integral() virtual override external view returns (uint) { return reward_integral_[rewarded_token]; } function reward_integral_for(address addr) virtual override external view returns (uint) { return reward_integral_for_[addr][rewarded_token]; } function rewards_for(address addr) virtual override external view returns (uint) { return rewards_for_[addr][rewarded_token]; } function claimed_rewards_for(address addr) virtual override external view returns (uint) { return claimed_rewards_for_[addr][rewarded_token]; } } contra uge is SExactGauge { address[] public rewards; //mapping(address => mapping(address =>uint)) internal sumRewardPerOf_; // recipient => rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_ //mapping(address => uint) internal sumRewardPer_; // rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_for_ function initialize(address governor, address _minter, address _lp_token, address _nestGauge, address[] memory _moreRewards) public initializer { super.initialize(governor, _minter, _lp_token); reward_contract = _nestGauge; rewarded_token = LiquidityGauge(_nestGauge).crv_token(); rewards = _moreRewards; rewards.push(rewarded_token); address rewarded_token2 = LiquidityGauge(_nestGauge).rewarded_token(); if(rewarded_token2 != address(0)) rewards.push(rewarded_token2); LiquidityGauge(_nestGauge).integrate_checkpoint(); // just check for(uint i=0; i<_moreRewards.length; i++) IERC20(_moreRewards[i]).totalSupply(); // just check } function _deposit(address from, uint amount) virtual override internal { super._deposit(from, amount); // lp_token.safeTransferFrom(from, address(this), amount); lp_token.safeApprove(reward_contract, amount); LiquidityGauge(reward_contract).deposit(amount); } function _withdraw(address to, uint amount) virtual override internal { LiquidityGauge(reward_contract).withdraw(amount); super._withdraw(to, amount); // lp_token.safeTransfer(to, amount); } function claim_rewards(address to) virtual override public { if(span == 0 || totalSupply == 0) return; _checkpoint_rewards(to, true); for(uint i=0; i<rewards.length; i++) { uint amount = rewards_for_[to][rewards[i]].sub(claimed_rewards_for_[to][rewards[i]]); if(amount > 0) { rewards[i].safeTransfer(to, amount); claimed_rewards_for_[to][rewards[i]] = rewards_for_[to][rewards[i]]; } } } function _checkpoint_rewards(address addr, bool _claim_rewards) virtual override internal { if(span == 0 || totalSupply == 0) return; uint[] memory drs = new uint[](rewards.length); if(_claim_rewards) { for(uint i=0; i<drs.length; i++) drs[i] = IERC20(rewards[i]).balanceOf(address(this)); Minter(LiquidityGauge(reward_contract).minter()).mint(reward_contract); LiquidityGauge(reward_contract).claim_rewards(); for(uint i=0; i<drs.length; i++) drs[i] = IERC20(rewards[i]).balanceOf(address(this)).sub(drs[i]); } for(uint i=0; i<drs.length; i++) { uint amount = _claimable_tokens(addr, drs[i], reward_integral_[rewards[i]], reward_integral_for_[msg.sender][rewards[i]]); if(amount > 0) rewards_for_[addr][rewards[i]] = rewards_for_[addr][rewards[i]].add(amount); if(drs[i] > 0) reward_integral_[rewards[i]] = reward_integral_[rewards[i]].add(drs[i].mul(1 ether).div(totalSupply)); if(reward_integral_for_[addr][rewards[i]] != reward_integral_[rewards[i]]) reward_integral_for_[addr][rewards[i]] = reward_integral_[rewards[i]]; } } function claimable_reward(address addr) virtual override public view returns (uint) { //uint delta = LiquidityGauge(reward_contract).claimable_tokens(address(this)); // Error: Mutable call in static context uint delta = LiquidityGauge(reward_contract).integrate_fraction(address(this)).sub(Minter(LiquidityGauge(reward_contract).minter()).minted(address(this), reward_contract)); return _claimable_tokens(addr, delta, reward_integral_[rewarded_token], reward_integral_for_[addr][rewarded_token]); } function claimable_reward2(address addr) virtual public view returns (uint) { uint delta = LiquidityGauge(reward_contract).claimable_reward(address(this)); address reward2 = LiquidityGauge(reward_contract).rewarded_token(); return _claimable_tokens(addr, delta, reward_integral_[reward2], reward_integral_for_[addr][reward2]); } function claimable_reward(address addr, address reward) virtual public view returns (uint) { return _claimable_tokens(addr, 0, reward_integral_[reward], reward_integral_for_[addr][reward]); } function claimed_rewards_for2(address addr) virtual public view returns (uint) { return claimed_rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()]; } function rewards_for2(address addr) virtual public view returns (uint) { return rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()]; } } contrac is Minter, Configurable { using SafeMath for uint; using Address for address payable; using TransferHelper for address; bytes32 internal constant _allowContract_ = 'allowContract'; bytes32 internal constant _allowlist_ = 'allowlist'; bytes32 internal constant _blocklist_ = 'blocklist'; address override public token; address override public controller; mapping(address => mapping(address => uint)) override public minted; // user => reward_contract => value mapping(address => mapping(address => bool)) override public allowed_to_mint_for; // minter => user => can mint? mapping(address => uint) public quotas; // reward_contract => quota; function initialize(address governor, address token_) public initializer { super.initialize(governor); token = token_; } function setGaugeQuota(address gauge, uint quota) public governance { quotas[gauge] = quota; } function mint(address gauge) virtual override public { mint_for(gauge, msg.sender); } function mint_many(address[8] calldata gauges) virtual override external { for(uint i=0; i<gauges.length; i++) mint(gauges[i]); } function mint_for(address gauge, address _for) virtual override public { require(_for == msg.sender || allowed_to_mint_for[msg.sender][_for], 'Not approved'); require(quotas[gauge] > 0, 'No quota'); require(getConfig(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfig(_allowlist_, msg.sender) != 0, 'No allowContract'); LiquidityGauge(gauge).user_checkpoint(_for); uint total_mint = LiquidityGauge(gauge).integrate_fraction(_for); uint to_mint = total_mint.sub(minted[_for][gauge]); if(to_mint != 0) { quotas[gauge] = quotas[gauge].sub(to_mint); token.safeTransfer(_for, to_mint); minted[_for][gauge] = total_mint; emit Minted(_for, gauge, total_mint); } } function toggle_approve_mint(address minting_user) virtual override external { allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[minting_user][msg.sender]; } } /* // he 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; } } 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; } function sqrt(uint x)public pure returns(uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } 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); } } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) public _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 public _totalSupply; string internal _name; string internal _symbol; 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) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract SfgToken is ERC20 { constructor(address SfgFarm) ERC20("Stable Finance Governance Token", "SFG") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfgFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } contract SfyToken is ERC20 { constructor(address SfyFarm) ERC20("Stable Finance Yield Token", "SFY") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfyFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
0x608060405234801561001057600080fd5b50600436106103db5760003560e01c806376d8b1171161020a578063c0c53b8b11610125578063e1522536116100b8578063f301af4211610087578063f301af4214610ac0578063f77c479114610add578063f8453e7c14610ae5578063fd96044b14610bb0578063fec8ee0c14610bd6576103db565b8063e152253614610a63578063e6f1daf214610a91578063ef78d4fd14610a99578063efbe1c1c14610ab8576103db565b8063d31f3f6d116100f4578063d31f3f6d14610a04578063ddf2be3f14610a0c578063de263bfa14610a35578063dfe0503114610a5b576103db565b8063c0c53b8b1461095a578063c4d66de814610992578063cdf10baf146109b8578063d2797b59146109de576103db565b80639bd324f21161019d578063b6aa515b1161016c578063b6aa515b14610907578063b6b55f251461092d578063be5d1be91461094a578063bf88a6ff14610952576103db565b80639bd324f2146108815780639df4ed56146108a7578063aaa626b6146108cd578063b21544f3146108d5576103db565b806387564d84116101d957806387564d84146107e55780638ec872e31461080a57806396c551751461082d578063972656a314610853576103db565b806376d8b117146107a757806381c0c263146107af57806382c63066146107b757806384e9bd7e146107bf576103db565b8063275f63e9116102fa5780634c87a0a51161028d5780636dd5b69d1161025c5780636dd5b69d1461071b5780636e553f651461073857806370a08231146107645780637598108c1461078a576103db565b80634c87a0a51461068b5780634d3ced19146106b957806352665f47146106e757806365fe945114610713576103db565b806338d07436116102c957806338d074361461061c5780633ccfd60b1461064157806343d7f86f146106495780634b82009314610651576103db565b8063275f63e9146105855780632e1a7d4d146105ab57806333134583146105c857806333fd6f74146105ee576103db565b806317e28089116103725780631d2747d4116103415780631d2747d41461052157806323a582921461054f5780632585581f14610557578063267716d21461055f576103db565b806317e28089146104e3578063180692d0146104eb57806318160ddd146104f35780631b9f546f146104fb576103db565b806313ecb1ca116103ae57806313ecb1ca1461046a57806313fa13681461049057806315fe96dc146104b657806316fa50b1146104db576103db565b806307546172146103e057806309400707146104045780630b54e7651461043c5780630c340a2414610462575b600080fd5b6103e8610bf3565b604080516001600160a01b039092168252519081900360200190f35b61042a6004803603602081101561041a57600080fd5b50356001600160a01b0316610c02565b60408051918252519081900360200190f35b61042a6004803603602081101561045257600080fd5b50356001600160a01b0316610c20565b6103e8610cdd565b61042a6004803603602081101561048057600080fd5b50356001600160a01b0316610cec565b61042a600480360360208110156104a657600080fd5b50356001600160a01b0316610cfe565b6104d9600480360360408110156104cc57600080fd5b5080359060200135610d42565b005b6103e8610d67565b61042a610d82565b61042a610d88565b61042a610d9a565b61042a6004803603602081101561051157600080fd5b50356001600160a01b0316610da0565b6104d96004803603604081101561053757600080fd5b506001600160a01b0381351690602001351515610dbe565b61042a610df4565b61042a610e06565b61042a6004803603602081101561057557600080fd5b50356001600160a01b0316610e18565b61042a6004803603602081101561059b57600080fd5b50356001600160a01b0316610e36565b6104d9600480360360208110156105c157600080fd5b5035610ea7565b61042a600480360360208110156105de57600080fd5b50356001600160a01b0316610eb5565b61042a6004803603604081101561060457600080fd5b506001600160a01b0381358116916020013516610f02565b6104d96004803603604081101561063257600080fd5b50803590602001351515610f63565b6104d9610fee565b61042a61100b565b6106776004803603602081101561066757600080fd5b50356001600160a01b031661101d565b604080519115158252519081900360200190f35b61042a600480360360408110156106a157600080fd5b506001600160a01b0381358116916020013516611032565b61042a600480360360408110156106cf57600080fd5b506001600160a01b038135811691602001351661105b565b61042a600480360360408110156106fd57600080fd5b50803590602001356001600160a01b0316611084565b61042a6110a0565b61042a6004803603602081101561073157600080fd5b50356110b2565b6104d96004803603604081101561074e57600080fd5b50803590602001356001600160a01b03166110c4565b61042a6004803603602081101561077a57600080fd5b50356001600160a01b03166111c7565b61042a600480360360208110156107a057600080fd5b50356111d9565b6103e86111f9565b6104d9611208565b6103e8611269565b6104d9600480360360208110156107d557600080fd5b50356001600160a01b0316611278565b6104d9600480360360408110156107fb57600080fd5b508035906020013515156114a1565b61042a6004803603604081101561082057600080fd5b508035906020013561150c565b6104d96004803603602081101561084357600080fd5b50356001600160a01b031661151f565b61042a6004803603604081101561086957600080fd5b506001600160a01b038135811691602001351661152a565b61042a6004803603602081101561089757600080fd5b50356001600160a01b0316611553565b61042a600480360360208110156108bd57600080fd5b50356001600160a01b0316611571565b61042a6115b5565b6104d9600480360360608110156108eb57600080fd5b508035906001600160a01b0360208201351690604001356115ec565b6104d96004803603602081101561091d57600080fd5b50356001600160a01b031661161d565b6104d96004803603602081101561094357600080fd5b503561163d565b61042a611647565b6103e861164d565b6104d96004803603606081101561097057600080fd5b506001600160a01b038135811691602081013582169160409091013516611668565b6104d9600480360360208110156109a857600080fd5b50356001600160a01b031661182a565b61042a600480360360208110156109ce57600080fd5b50356001600160a01b031661191b565b61042a600480360360208110156109f457600080fd5b50356001600160a01b0316611a87565b61042a611c8f565b6104d960048036036060811015610a2257600080fd5b5080359060208101359060400135611ca1565b61042a60048036036020811015610a4b57600080fd5b50356001600160a01b0316611cc4565b6103e8611ce2565b61067760048036036040811015610a7957600080fd5b506001600160a01b0381358116916020013516611cf1565b6104d9611d11565b610aa1611d1a565b60408051600f9290920b8252519081900360200190f35b61042a611d23565b6103e860048036036020811015610ad657600080fd5b5035611d35565b6103e8611d68565b6104d9600480360360a0811015610afb57600080fd5b6001600160a01b03823581169260208101358216926040820135831692606083013516919081019060a081016080820135640100000000811115610b3e57600080fd5b820183602082011115610b5057600080fd5b80359060200191846020830284011164010000000083111715610b7257600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550611d77945050505050565b61042a60048036036020811015610bc657600080fd5b50356001600160a01b031661212a565b61042a60048036036020811015610bec57600080fd5b503561216e565b6035546001600160a01b031681565b6c02863c1f5cdae42f95400000436020526000908152604090205481565b6001600160a01b0380821660009081526c02863c1f5cdae42f9540000049602090815260408083206c02863c1f5cdae42f95400000455482516316fa50b160e01b8152925194959194869491909216926316fa50b19260048083019392829003018186803b158015610c9157600080fd5b505afa158015610ca5573d6000803e3d6000fd5b505050506040513d6020811015610cbb57600080fd5b50516001600160a01b0316815260208101919091526040016000205492915050565b6033546001600160a01b031681565b603e6020526000908152604090205481565b6001600160a01b0390811660009081526c02863c1f5cdae42f9540000048602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6033546001600160a01b03163314610d5957600080fd5b610d638282612193565b5050565b6c02863c1f5cdae42f9540000046546001600160a01b031681565b603f5481565b6c02863c1f5cdae42f95400000445481565b603b5481565b6c02863c1f5cdae42f954000004d6020526000908152604090205481565b6001600160a01b03919091166000908152603d602090815260408083203384529091529020805460ff1916911515919091179055565b6c02863c1f5cdae42f95400000505481565b6c02863c1f5cdae42f954000004b5481565b6c02863c1f5cdae42f95400000476020526000908152604090205481565b6001600160a01b0380821660009081526c02863c1f5cdae42f954000004a602090815260408083206c02863c1f5cdae42f95400000455482516316fa50b160e01b8152925194959194869491909216926316fa50b19260048083019392829003018186803b158015610c9157600080fd5b610eb2816001610f63565b50565b6000610efc82610ec36121ba565b6c02863c1f5cdae42f954000004e546001600160a01b03861660009081526c02863c1f5cdae42f954000004d6020526040902054612345565b92915050565b6001600160a01b0380821660008181526c02863c1f5cdae42f9540000047602090815260408083205494871683526c02863c1f5cdae42f95400000488252808320938352929052908120549091610f5c9185918491612345565b9392505050565b610f6d33826123e6565b603b54610f7a9083612582565b603b55336000908152603a6020526040902054610f979083612582565b336000818152603a6020526040902091909155610fb490836125c4565b60408051838152905133917f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364919081900360200190a25050565b336000908152603a6020526040902054611009906001610f63565b565b6c02863c1f5cdae42f954000004f5481565b600061102a8260016123e6565b506001919050565b6c02863c1f5cdae42f954000004860209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f954000004a60209081526000928352604080842090915290825290205481565b6001600160a01b03161860009081526034602052604090205490565b6c02863c1f5cdae42f954000004e5481565b60009081526034602052604090205490565b6001600160a01b0381163314806110fe5750336000908152603d602090815260408083206001600160a01b038516845290915290205460ff165b61113e576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b6111498160016123e6565b611153818361263f565b336000908152603a602052604090205461116d90836126df565b336000908152603a6020526040902055603b5461118a90836126df565b603b5560408051838152905133917fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c919081900360200190a25050565b603a6020526000908152604090205481565b6041816c01431e0fae6d7217caa000000081106111f257fe5b0154905081565b6036546001600160a01b031681565b6033546001600160a01b0316331461121f57600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b6037546001600160a01b031681565b6c02863c1f5cdae42f954000004b5415806112935750603b54155b1561129d57610eb2565b6112a8816001612739565b60005b6c02863c1f5cdae42f954000005154811015610d63576001600160a01b03821660009081526c02863c1f5cdae42f954000004a602052604081206c02863c1f5cdae42f95400000518054611390929184918690811061130657fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493881682526c02863c1f5cdae42f954000004990529081206c02863c1f5cdae42f954000005180549192918790811061136557fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205490612582565b90508015611498576113d283826c02863c1f5cdae42f954000005185815481106113b657fe5b6000918252602090912001546001600160a01b03169190612e86565b6001600160a01b03831660009081526c02863c1f5cdae42f9540000049602052604081206c02863c1f5cdae42f954000005180549192918590811061141357fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493871682526c02863c1f5cdae42f954000004a90529081206c02863c1f5cdae42f954000005180549192918690811061147257fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b506001016112ab565b6033546001600160a01b031633146114b857600080fd5b6c02863c1f5cdae42f954000004b82905580156114e6574282016c02863c1f5cdae42f954000004c556114f8565b60006c02863c1f5cdae42f954000004c555b5050426c02863c1f5cdae42f954000005055565b1860009081526034602052604090205490565b610eb28160016123e6565b6c02863c1f5cdae42f954000004960209081526000928352604080842090915290825290205481565b6c02863c1f5cdae42f95400000426020526000908152604090205481565b6001600160a01b0390811660009081526c02863c1f5cdae42f9540000049602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c02863c1f5cdae42f9540000046546001600160a01b031660009081526c02863c1f5cdae42f954000004760205260409020545b90565b6033546001600160a01b0316331461160357600080fd5b6116186001600160a01b038316841882612193565b505050565b6033546001600160a01b0316331461163457600080fd5b610eb281612ff0565b610eb281336110c4565b603c5481565b6c02863c1f5cdae42f9540000045546001600160a01b031681565b600054610100900460ff1680611681575061168161305f565b8061168f575060005460ff16155b6116ca5760405162461bcd60e51b815260040180806020018281038252602e81526020018061377c602e913960400191505060405180910390fd5b600054610100900460ff161580156116f5576000805460ff1961ff0019909116610100171660011790555b6116fe8461182a565b603580546001600160a01b0319166001600160a01b03851690811790915560408051637e062a3560e11b8152905163fc0c546a91600480820192602092909190829003018186803b15801561175257600080fd5b505afa158015611766573d6000803e3d6000fd5b505050506040513d602081101561177c57600080fd5b5051603680546001600160a01b03199081166001600160a01b0393841617909155603780549091168483161790819055604080516318160ddd60e01b8152905191909216916318160ddd916004808301926020929190829003018186803b1580156117e657600080fd5b505afa1580156117fa573d6000803e3d6000fd5b505050506040513d602081101561181057600080fd5b50508015611824576000805461ff00191690555b50505050565b600054610100900460ff1680611843575061184361305f565b80611851575060005460ff16155b61188c5760405162461bcd60e51b815260040180806020018281038252602e81526020018061377c602e913960400191505060405180910390fd5b600054610100900460ff161580156118b7576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a38015610d63576000805461ff00191690555050565b6c02863c1f5cdae42f9540000045546040805163d2797b5960e01b8152306004820152905160009283926001600160a01b039091169163d2797b5991602480820192602092909190829003018186803b15801561197757600080fd5b505afa15801561198b573d6000803e3d6000fd5b505050506040513d60208110156119a157600080fd5b50516c02863c1f5cdae42f954000004554604080516316fa50b160e01b815290519293506000926001600160a01b03909216916316fa50b191600480820192602092909190829003018186803b1580156119fa57600080fd5b505afa158015611a0e573d6000803e3d6000fd5b505050506040513d6020811015611a2457600080fd5b50516001600160a01b0380821660008181526c02863c1f5cdae42f95400000476020908152604080832054948a1683526c02863c1f5cdae42f954000004882528083209383529290522054919250611a7f9186918591612345565b949350505050565b600080611c276c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663075461726040518163ffffffff1660e01b815260040160206040518083038186803b158015611ae757600080fd5b505afa158015611afb573d6000803e3d6000fd5b505050506040513d6020811015611b1157600080fd5b50516c02863c1f5cdae42f954000004554604080516308b752bb60e41b81523060048201526001600160a01b03928316602482015290519190921691638b752bb0916044808301926020929190829003018186803b158015611b7257600080fd5b505afa158015611b86573d6000803e3d6000fd5b505050506040513d6020811015611b9c57600080fd5b50516c02863c1f5cdae42f95400000455460408051630940070760e01b815230600482015290516001600160a01b0390921691630940070791602480820192602092909190829003018186803b158015611bf557600080fd5b505afa158015611c09573d6000803e3d6000fd5b505050506040513d6020811015611c1f57600080fd5b505190612582565b6c02863c1f5cdae42f9540000046546001600160a01b0390811660008181526c02863c1f5cdae42f9540000047602090815260408083205494891683526c02863c1f5cdae42f954000004882528083209383529290522054919250610f5c9185918491612345565b6c02863c1f5cdae42f95400000505490565b6033546001600160a01b03163314611cb857600080fd5b61161883831882612193565b6c02863c1f5cdae42f95400000416020526000908152604090205481565b6039546001600160a01b031681565b603d60209081526000928352604080842090915290825290205460ff1681565b61100933611278565b604054600f0b81565b6c02863c1f5cdae42f954000004c5481565b6c02863c1f5cdae42f95400000518181548110611d4e57fe5b6000918252602090912001546001600160a01b0316905081565b6038546001600160a01b031681565b600054610100900460ff1680611d905750611d9061305f565b80611d9e575060005460ff16155b611dd95760405162461bcd60e51b815260040180806020018281038252602e81526020018061377c602e913960400191505060405180910390fd5b600054610100900460ff16158015611e04576000805460ff1961ff0019909116610100171660011790555b611e0f868686611668565b6c02863c1f5cdae42f954000004580546001600160a01b0319166001600160a01b038516908117909155604080516376d8b11760e01b815290516376d8b11791600480820192602092909190829003018186803b158015611e6f57600080fd5b505afa158015611e83573d6000803e3d6000fd5b505050506040513d6020811015611e9957600080fd5b50516c02863c1f5cdae42f954000004680546001600160a01b0319166001600160a01b039092169190911790558151611ee5906c02863c1f5cdae42f95400000519060208501906136d6565b506c02863c1f5cdae42f9540000046546c02863c1f5cdae42f9540000051805460018101825560009182527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b03938416179055604080516316fa50b160e01b8152905191928616916316fa50b191600480820192602092909190829003018186803b158015611f8757600080fd5b505afa158015611f9b573d6000803e3d6000fd5b505050506040513d6020811015611fb157600080fd5b505190506001600160a01b0381161561201c576c02863c1f5cdae42f954000005180546001810182556000919091527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b0383161790555b836001600160a01b031663d31f3f6d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561205557600080fd5b505afa158015612069573d6000803e3d6000fd5b505050506040513d602081101561207f57600080fd5b50600090505b835181101561210e5783818151811061209a57fe5b60200260200101516001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156120da57600080fd5b505afa1580156120ee573d6000803e3d6000fd5b505050506040513d602081101561210457600080fd5b5050600101612085565b50508015612122576000805461ff00191690555b505050505050565b6001600160a01b0390811660009081526c02863c1f5cdae42f954000004a602090815260408083206c02863c1f5cdae42f9540000046549094168352929052205490565b6c01431e0fae6d7217caa0000041816c01431e0fae6d7217caa000000081106111f257fe5b6000828152603460205260409020548114610d635760009182526034602052604090912055565b6c02863c1f5cdae42f954000004f546035546040805163c33342e960e01b8152306004820152905160009361221d9390926001600160a01b039091169163c33342e991602480820192602092909190829003018186803b158015611bf557600080fd5b90506c02863c1f5cdae42f954000004c54600014156122b0576c02863c1f5cdae42f954000004b546c02863c1f5cdae42f95400000505461225f904290612582565b10156122ab576122a86c02863c1f5cdae42f954000004b546122a261229b6c02863c1f5cdae42f9540000050544261258290919063ffffffff16565b8490613065565b906130be565b90505b6115e9565b6c02863c1f5cdae42f954000004c5442101561231c576122a86122f86c02863c1f5cdae42f9540000050546c02863c1f5cdae42f954000004c5461258290919063ffffffff16565b6122a261229b6c02863c1f5cdae42f9540000050544261258290919063ffffffff16565b6c02863c1f5cdae42f954000004c546c02863c1f5cdae42f954000005054106115e95750600090565b60006c02863c1f5cdae42f954000004b54600014806123645750603b54155b1561237157506000611a7f565b61237b8383612582565b90506123a86123a1603b546122a2670de0b6b3a76400008861306590919063ffffffff16565b82906126df565b6001600160a01b0386166000908152603a60205260409020549091506123dd90670de0b6b3a7640000906122a2908490613065565b95945050505050565b6c02863c1f5cdae42f954000004b5415806124015750603b54155b1561240b57610d63565b60006124156121ba565b9050600061246484836c02863c1f5cdae42f954000004e546c02863c1f5cdae42f954000004d6000896001600160a01b03166001600160a01b0316815260200190815260200160002054612345565b90508082146124a85761249881612492846c02863c1f5cdae42f954000004f546126df90919063ffffffff16565b90612582565b6c02863c1f5cdae42f954000004f555b81156124f057603b546124e0906124cb906122a285670de0b6b3a7640000613065565b6c02863c1f5cdae42f954000004e54906126df565b6c02863c1f5cdae42f954000004e555b6c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020541461255e576c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020555b426c02863c1f5cdae42f9540000050556125788482613100565b6118248484612739565b6000610f5c83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506132f3565b6c02863c1f5cdae42f95400000455460408051632e1a7d4d60e01b81526004810184905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b15801561261d57600080fd5b505af1158015612631573d6000803e3d6000fd5b50505050610d63828261338a565b61264982826133a1565b6c02863c1f5cdae42f954000004554603754612672916001600160a01b039182169116836133b9565b6c02863c1f5cdae42f9540000045546040805163b6b55f2560e01b81526004810184905290516001600160a01b039092169163b6b55f259160248082019260009290919082900301818387803b1580156126cb57600080fd5b505af1158015612122573d6000803e3d6000fd5b600082820183811015610f5c576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6c02863c1f5cdae42f954000004b5415806127545750603b54155b1561275e57610d63565b6c02863c1f5cdae42f95400000515460609067ffffffffffffffff8111801561278657600080fd5b506040519080825280602002602001820160405280156127b0578160200160208202803683370190505b5090508115612a935760005b815181101561287a576c02863c1f5cdae42f954000005181815481106127de57fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b15801561282d57600080fd5b505afa158015612841573d6000803e3d6000fd5b505050506040513d602081101561285757600080fd5b5051825183908390811061286757fe5b60209081029190910101526001016127bc565b506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663075461726040518163ffffffff1660e01b815260040160206040518083038186803b1580156128d557600080fd5b505afa1580156128e9573d6000803e3d6000fd5b505050506040513d60208110156128ff57600080fd5b50516c02863c1f5cdae42f954000004554604080516335313c2160e11b81526001600160a01b03928316600482015290519190921691636a62784291602480830192600092919082900301818387803b15801561295b57600080fd5b505af115801561296f573d6000803e3d6000fd5b505050506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663e6f1daf26040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156129cf57600080fd5b505af11580156129e3573d6000803e3d6000fd5b5050505060005b8151811015612a9157612a72828281518110612a0257fe5b60200260200101516c02863c1f5cdae42f95400000518381548110612a2357fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b158015611bf557600080fd5b828281518110612a7e57fe5b60209081029190910101526001016129ea565b505b60005b8151811015611824576000612b6885848481518110612ab157fe5b60200260200101516c02863c1f5cdae42f954000004760006c02863c1f5cdae42f95400000518781548110612ae257fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120543382526c02863c1f5cdae42f95400000489093529081206c02863c1f5cdae42f9540000051805491929189908110612b3e57fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902054612345565b90508015612c5257612beb816c02863c1f5cdae42f95400000496000886001600160a01b03166001600160a01b0316815260200190815260200160002060006c02863c1f5cdae42f95400000518681548110612bc057fe5b60009182526020808320909101546001600160a01b03168352820192909252604001902054906126df565b6001600160a01b03861660009081526c02863c1f5cdae42f9540000049602052604081206c02863c1f5cdae42f9540000051805491929186908110612c2c57fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b6000838381518110612c6057fe5b60200260200101511115612d1d57612cce612ca5603b546122a2670de0b6b3a7640000878781518110612c8f57fe5b602002602001015161306590919063ffffffff16565b6c02863c1f5cdae42f954000004760006c02863c1f5cdae42f95400000518681548110612bc057fe5b6c02863c1f5cdae42f954000004760006c02863c1f5cdae42f95400000518581548110612cf757fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b6c02863c1f5cdae42f954000004760006c02863c1f5cdae42f95400000518481548110612d4657fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493891682526c02863c1f5cdae42f954000004890529081206c02863c1f5cdae42f9540000051805491929186908110612da557fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205414612e7d576c02863c1f5cdae42f954000004760006c02863c1f5cdae42f95400000518481548110612df857fe5b60009182526020808320909101546001600160a01b03908116845283820194909452604092830182205493891682526c02863c1f5cdae42f954000004890529081206c02863c1f5cdae42f9540000051805491929186908110612e5757fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b50600101612a96565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b60208310612f035780518252601f199092019160209182019101612ee4565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612f65576040519150601f19603f3d011682016040523d82523d6000602084013e612f6a565b606091505b5091509150818015612f98575080511580612f985750808060200190516020811015612f9557600080fd5b50515b612fe9576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b5050505050565b6001600160a01b03811661300357600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b303b1590565b60008261307457506000610efc565b8282028284828161308157fe5b0414610f5c5760405162461bcd60e51b815260040180806020018281038252602181526020018061375b6021913960400191505060405180910390fd5b6000610f5c83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061351c565b8015610d63576001600160a01b03821660009081526c02863c1f5cdae42f9540000043602052604090205461313590826126df565b6001600160a01b0392831660009081526c02863c1f5cdae42f95400000436020908152604082209290925560349091527fe9b68ca2b566af5bdfbb3361c12fcbb5dbf956c250bbd74cc175cc06ec62c7915467646576526174696f60c01b9091527fb8fbd2e70438ec482a0e7fc9b87580647182c1694aea1065027a1d634e92d6b95490928316158015906131c957508015155b15613238576132126131e7670de0b6b3a76400006122a28585613065565b6001600160a01b03851660009081526c02863c1f5cdae42f95400000436020526040902054906126df565b6001600160a01b03841660009081526c02863c1f5cdae42f954000004360205260409020555b5060346020527f82e0b58992d24d827851dcbd63485b5933f9d3ae4c2ca50477d1437e73f6d342546765636f526174696f60c01b6000527ffc6561c6b7742261fbeab673eba1bedd2f5b1d7221f757ea8c9a87d664cfbed2549092506001600160a01b038316158015906132ab57508015155b15611618576132c96131e7670de0b6b3a76400006122a28585613065565b6001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902055505050565b600081848411156133825760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561334757818101518382015260200161332f565b50505050905090810190601f1680156133745780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b603754610d63906001600160a01b03168383612e86565b603754610d63906001600160a01b0316833084613581565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663095ea7b360e01b178152925182516000946060949389169392918291908083835b602083106134365780518252601f199092019160209182019101613417565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613498576040519150601f19603f3d011682016040523d82523d6000602084013e61349d565b606091505b50915091508180156134cb5750805115806134cb57508080602001905160208110156134c857600080fd5b50515b612fe9576040805162461bcd60e51b815260206004820152601e60248201527f5472616e7366657248656c7065723a20415050524f56455f4641494c45440000604482015290519081900360640190fd5b6000818361356b5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561334757818101518382015260200161332f565b50600083858161357757fe5b0495945050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17815292518251600094606094938a169392918291908083835b602083106136065780518252601f1990920191602091820191016135e7565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613668576040519150601f19603f3d011682016040523d82523d6000602084013e61366d565b606091505b509150915081801561369b57508051158061369b575080806020019051602081101561369857600080fd5b50515b6121225760405162461bcd60e51b81526004018080602001828103825260248152602001806137aa6024913960400191505060405180910390fd5b82805482825590600052602060002090810192821561372b579160200282015b8281111561372b57825182546001600160a01b0319166001600160a01b039091161782556020909201916001909101906136f6565b5061373792915061373b565b5090565b5b808211156137375780546001600160a01b031916815560010161373c56fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c4544a2646970667358221220b5876359b1ded8699b04ae46a3398c317b7365121b018b0b5ba351be73838e3364736f6c634300060c0033
[ 5, 4, 9, 7 ]
0x553C469A4b2be93f91692ddFAb6587B623f91279
pragma solidity 0.6.8; 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 vaults 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract CryptoPunksMarket { address owner; string public standard = "CryptoPunks"; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public nextPunkIndexToAssign = 0; bool public allPunksAssigned = false; uint256 public punksRemainingToAssign = 0; //mapping (address => uint) public addressToPunkIndex; mapping(uint256 => address) public punkIndexToAddress; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } // A record of punks that are offered for sale at a specific minimum value, and perhaps to a specific person mapping(uint256 => Offer) public punksOfferedForSale; // A record of the highest punk bid mapping(uint256 => Bid) public punkBids; mapping(address => uint256) public pendingWithdrawals; event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public payable { // balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens owner = msg.sender; totalSupply = 10000; // Update total supply punksRemainingToAssign = totalSupply; name = "CRYPTOPUNKS"; // Set the name for display purposes symbol = "Ͼ"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes } function setInitialOwner(address to, uint256 punkIndex) public { // require(msg.sender == owner, "msg.sender != owner"); require(!allPunksAssigned); require(punkIndex < 10000); if (punkIndexToAddress[punkIndex] != to) { if (punkIndexToAddress[punkIndex] != address(0)) { balanceOf[punkIndexToAddress[punkIndex]]--; } else { punksRemainingToAssign--; } punkIndexToAddress[punkIndex] = to; balanceOf[to]++; emit PunkTransfer(address(0), to, punkIndex); } } function setInitialOwners( address[] memory addresses, uint256[] memory indices ) public { require(msg.sender == owner); uint256 n = addresses.length; for (uint256 i = 0; i < n; i++) { setInitialOwner(addresses[i], indices[i]); } } function allInitialOwnersAssigned() public { require(msg.sender == owner); allPunksAssigned = true; } function getPunk(uint256 punkIndex) public { // require(allPunksAssigned); require(punksRemainingToAssign != 0); require(punkIndexToAddress[punkIndex] == address(0)); require(punkIndex < 10000); punkIndexToAddress[punkIndex] = msg.sender; balanceOf[msg.sender]++; punksRemainingToAssign--; emit Assign(msg.sender, punkIndex); } // Transfer ownership of a punk to another user without requiring payment function transferPunk(address to, uint256 punkIndex) public { // // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); if (punksOfferedForSale[punkIndex].isForSale) { punkNoLongerForSale(punkIndex); } punkIndexToAddress[punkIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; emit Transfer(msg.sender, to, 1); emit PunkTransfer(msg.sender, to, punkIndex); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == to) { // Kill bid and revault value pendingWithdrawals[to] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function punkNoLongerForSale(uint256 punkIndex) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, msg.sender, 0, address(0) ); emit PunkNoLongerForSale(punkIndex); } function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, address(0) ); emit PunkOffered(punkIndex, minSalePriceInWei, address(0)); } function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, toAddress ); emit PunkOffered(punkIndex, minSalePriceInWei, toAddress); } function buyPunk(uint256 punkIndex) public payable { // require(allPunksAssigned); Offer storage offer = punksOfferedForSale[punkIndex]; require(punkIndex < 10000); require(offer.isForSale); // punk not actually for sale (offer.onlySellTo == address(0) || offer.onlySellTo == msg.sender); // punk not supposed to be sold to this user require(msg.value >= offer.minValue); // Didn't send enough ETH require(offer.seller == punkIndexToAddress[punkIndex]); // Seller no longer owner of punk address seller = offer.seller; punkIndexToAddress[punkIndex] = msg.sender; balanceOf[seller]--; balanceOf[msg.sender]++; emit Transfer(seller, msg.sender, 1); punkNoLongerForSale(punkIndex); pendingWithdrawals[seller] += msg.value; emit PunkBought(punkIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == msg.sender) { // Kill bid and revault value pendingWithdrawals[msg.sender] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function withdraw() public { // require(allPunksAssigned); uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending revault before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } function enterBidForPunk(uint256 punkIndex) public payable { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); require(msg.value != 0); Bid storage existing = punkBids[punkIndex]; require(msg.value > existing.value); if (existing.value > 0) { // Revault the failing bid pendingWithdrawals[existing.bidder] += existing.value; } punkBids[punkIndex] = Bid(true, punkIndex, msg.sender, msg.value); emit PunkBidEntered(punkIndex, msg.value, msg.sender); } function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); address seller = msg.sender; Bid storage bid = punkBids[punkIndex]; require(bid.value != 0); require(bid.value >= minPrice); punkIndexToAddress[punkIndex] = bid.bidder; balanceOf[seller]--; balanceOf[bid.bidder]++; emit Transfer(seller, bid.bidder, 1); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, bid.bidder, 0, address(0) ); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); pendingWithdrawals[seller] += amount; emit PunkBought(punkIndex, bid.value, seller, bid.bidder); } function withdrawBidForPunk(uint256 punkIndex) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); Bid storage bid = punkBids[punkIndex]; require(bid.bidder == msg.sender); emit PunkBidWithdrawn(punkIndex, bid.value, msg.sender); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); // Revault the bid money msg.sender.transfer(amount); } } 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)); } } interface ICryptoPunksMarket { struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; address onlySellTo; } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); function setInitialOwner(address to, uint256 punkIndex) external; function setInitialOwners( address[] calldata addresses, uint256[] calldata indices ) external; function allInitialOwnersAssigned() external; function getPunk(uint256 punkIndex) external; function transferPunk(address to, uint256 punkIndex) external; function punkNoLongerForSale(uint256 punkIndex) external; function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) external; function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) external; function buyPunk(uint256 punkIndex) external; function withdraw() external; function enterBidForPunk(uint256 punkIndex) external; function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) external; function withdrawBidForPunk(uint256 punkIndex) external; function punkIndexToAddress(uint256 punkIndex) external returns (address); function punksOfferedForSale(uint256 punkIndex) external returns ( bool isForSale, uint256 _punkIndex, address seller, uint256 minValue, address onlySellTo ); function balanceOf(address user) external returns (uint256); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IPunkToken is IERC20 { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function mint(address to, uint256 amount) external; function changeName(string calldata name) external; function changeSymbol(string calldata symbol) external; function setVaultAddress(address vaultAddress) external; function transferOwnership(address newOwner) external; } 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; } } contract Pausable is Ownable { bool private isPaused = false; event Paused(); event Unpaused(); function getIsPaused() public view returns (bool) { return isPaused; } function pause() public onlyOwner { isPaused = true; } function unpause() public onlyOwner { isPaused = false; } modifier whenPaused { require(isPaused, "Contract is not paused"); _; } modifier whenNotPaused { require(!isPaused, "Contract is paused"); _; } } contract PunkVaultBase is Pausable { address private erc20Address; address private cpmAddress; IPunkToken private erc20; ICryptoPunksMarket private cpm; function getERC20Address() public view returns (address) { return erc20Address; } function getCpmAddress() public view returns (address) { return cpmAddress; } function getERC20() internal view returns (IPunkToken) { return erc20; } function getCPM() internal view returns (ICryptoPunksMarket) { return cpm; } function setERC20Address(address newAddress) internal { require(erc20Address == address(0), "Already initialized ERC20"); erc20Address = newAddress; erc20 = IPunkToken(erc20Address); } function setCpmAddress(address newAddress) internal { require(cpmAddress == address(0), "Already initialized CPM"); cpmAddress = newAddress; cpm = ICryptoPunksMarket(cpmAddress); } } 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 revault on every call to nonReentrant will be lower in // amount. Since revaults 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 revault 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 revault is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _changeName(string memory name_) internal { _name = name_; } function _changeSymbol(string memory symbol_) internal { _symbol = symbol_; } /** * @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 {} } abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } contract PunkToken is Context, Ownable, ERC20Burnable { address private vaultAddress; constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _mint(msg.sender, 0); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function changeName(string memory name) public onlyOwner { _changeName(name); } function changeSymbol(string memory symbol) public onlyOwner { _changeSymbol(symbol); } function getVaultAddress() public view returns (address) { return vaultAddress; } function setVaultAddress(address newAddress) public onlyOwner { vaultAddress = newAddress; } } contract PunkVaultSafe is PunkVaultBase, ReentrancyGuard { using EnumerableSet for EnumerableSet.UintSet; EnumerableSet.UintSet private reserves; bool private inSafeMode = true; event TokenBurnedSafely(uint256 punkId, address indexed to); function getReserves() internal view returns (EnumerableSet.UintSet storage) { return reserves; } function getInSafeMode() public view returns (bool) { return inSafeMode; } function turnOffSafeMode() public onlyOwner { inSafeMode = false; } function turnOnSafeMode() public onlyOwner { inSafeMode = true; } modifier whenNotInSafeMode { require(!inSafeMode, "Contract is in safe mode"); _; } function simpleRedeem() public whenPaused nonReentrant { require( getERC20().balanceOf(msg.sender) >= 10**18, "ERC20 balance too small" ); require( getERC20().allowance(msg.sender, address(this)) >= 10**18, "ERC20 allowance too small" ); uint256 tokenId = reserves.at(0); getERC20().burnFrom(msg.sender, 10**18); reserves.remove(tokenId); getCPM().transferPunk(msg.sender, tokenId); emit TokenBurnedSafely(tokenId, msg.sender); } } contract Timelocked is PunkVaultSafe { using SafeMath for uint256; enum Timelock {Short, Medium, Long} uint256 private securityLevel; function getSecurityLevel() public view returns (string memory) { if (securityLevel == 0) { return "red"; } else if (securityLevel == 1) { return "orange"; } else if (securityLevel == 2) { return "yellow"; } else { return "green"; } } function increaseSecurityLevel() public onlyOwner { require(securityLevel < 3, "Already max"); securityLevel = securityLevel + 1; } function timeInDays(uint256 num) internal pure returns (uint256) { return num * 60 * 60 * 24; } function getDelay(Timelock lockId) public view returns (uint256) { if (securityLevel == 0) { return 2; // for testing } if (lockId == Timelock.Short) { if (securityLevel == 1) { return timeInDays(1); } else if (securityLevel == 2) { return timeInDays(2); } else { return timeInDays(3); } } else if (lockId == Timelock.Medium) { if (securityLevel == 1) { return timeInDays(2); } else if (securityLevel == 2) { return timeInDays(3); } else { return timeInDays(5); } } else { if (securityLevel == 1) { return timeInDays(3); } else if (securityLevel == 2) { return timeInDays(5); } else { return timeInDays(10); } } } mapping(Timelock => uint256) private releaseTimes; event Locked(Timelock lockId); event UnlockInitiated(Timelock lockId, uint256 whenUnlocked); function getReleaseTime(Timelock lockId) public view returns (uint256) { return releaseTimes[lockId]; } function initiateUnlock(Timelock lockId) public onlyOwner { uint256 newReleaseTime = now.add(getDelay(lockId)); releaseTimes[lockId] = newReleaseTime; emit UnlockInitiated(lockId, newReleaseTime); } function lock(Timelock lockId) public onlyOwner { releaseTimes[lockId] = 0; emit Locked(lockId); } modifier whenNotLockedS { uint256 releaseTime = releaseTimes[Timelock.Short]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedM { uint256 releaseTime = releaseTimes[Timelock.Medium]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedL { uint256 releaseTime = releaseTimes[Timelock.Long]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } } contract Profitable is Timelocked { mapping(address => bool) private verifiedIntegrators; uint256 private numIntegrators = 0; uint256[] private mintFees = [0, 0, 0]; uint256[] private burnFees = [0, 0, 0]; uint256[] private dualFees = [0, 0, 0]; uint256[] private supplierBounty = [(5 * 10**17), 10]; event MintFeesSet(uint256[] mintFees); event BurnFeesSet(uint256[] burnFees); event DualFeesSet(uint256[] dualFees); event SupplierBountySet(uint256[] supplierBounty); event IntegratorSet(address account, bool isVerified); event Withdrawal(address to, uint256 amount); function getMintFees() public view returns (uint256[] memory) { return mintFees; } function getBurnFees() public view returns (uint256[] memory) { return burnFees; } function getDualFees() public view returns (uint256[] memory) { return dualFees; } function getSupplierBounty() public view returns (uint256[] memory) { return supplierBounty; } function _getMintFees() internal view returns (uint256[] storage) { return mintFees; } function _getBurnFees() internal view returns (uint256[] storage) { return burnFees; } function _getDualFees() internal view returns (uint256[] storage) { return dualFees; } function setMintFees(uint256[] memory newMintFees) public onlyOwner whenNotLockedM { require(newMintFees.length == 3, "Wrong length"); mintFees = newMintFees; emit MintFeesSet(newMintFees); } function setBurnFees(uint256[] memory newBurnFees) public onlyOwner whenNotLockedL { require(newBurnFees.length == 3, "Wrong length"); burnFees = newBurnFees; emit BurnFeesSet(newBurnFees); } function setDualFees(uint256[] memory newDualFees) public onlyOwner whenNotLockedM { require(newDualFees.length == 3, "Wrong length"); dualFees = newDualFees; emit DualFeesSet(newDualFees); } function setSupplierBounty(uint256[] memory newSupplierBounty) public onlyOwner whenNotLockedL { require(newSupplierBounty.length == 2, "Wrong length"); supplierBounty = newSupplierBounty; emit SupplierBountySet(newSupplierBounty); } function isIntegrator(address account) public view returns (bool) { return verifiedIntegrators[account]; } function getNumIntegrators() public view returns (uint256) { return numIntegrators; } function setIntegrator(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedIntegrators[account], "Already set"); if (isVerified) { numIntegrators = numIntegrators.add(1); } else { numIntegrators = numIntegrators.sub(1); } verifiedIntegrators[account] = isVerified; emit IntegratorSet(account, isVerified); } function getFee(address account, uint256 numTokens, uint256[] storage fees) internal view returns (uint256) { uint256 fee = 0; if (verifiedIntegrators[account]) { return 0; } else if (numTokens == 1) { fee = fees[0]; } else { fee = fees[1] + numTokens * fees[2]; } return fee; } function getBurnBounty(uint256 numTokens) internal view returns (uint256) { uint256 bounty = 0; uint256 reservesLength = getReserves().length(); uint256 padding = supplierBounty[1]; if (reservesLength - numTokens <= padding) { uint256 addedAmount = 0; for (uint256 i = 0; i < numTokens; i++) { if (reservesLength - i <= padding && reservesLength - i > 0) { addedAmount += (supplierBounty[0] * (padding - (reservesLength - i) + 1)); } } bounty += addedAmount; } return bounty; } function getMintBounty(uint256 numTokens) internal view returns (uint256) { uint256 bounty = 0; uint256 reservesLength = getReserves().length(); uint256 padding = supplierBounty[1]; if (reservesLength <= padding) { uint256 addedAmount = 0; for (uint256 i = 0; i < numTokens; i++) { if (reservesLength + i <= padding) { addedAmount += (supplierBounty[0] * (padding - (reservesLength + i))); } } bounty += addedAmount; } return bounty; } function withdraw(address payable to) public onlyOwner whenNotLockedM { uint256 balance = address(this).balance; to.transfer(balance); emit Withdrawal(to, balance); } } contract Controllable is Profitable { mapping(address => bool) private verifiedControllers; uint256 private numControllers = 0; event ControllerSet(address account, bool isVerified); event DirectRedemption(uint256 punkId, address by, address indexed to); function isController(address account) public view returns (bool) { return verifiedControllers[account]; } function getNumControllers() public view returns (uint256) { return numControllers; } function setController(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedControllers[account], "Already set"); if (isVerified) { numControllers++; } else { numControllers--; } verifiedControllers[account] = isVerified; emit ControllerSet(account, isVerified); } modifier onlyController() { require(isController(_msgSender()), "Not a controller"); _; } function directRedeem(uint256 tokenId, address to) public onlyController { require(getERC20().balanceOf(to) >= 10**18, "ERC20 balance too small"); bool toSelf = (to == address(this)); require( toSelf || (getERC20().allowance(to, address(this)) >= 10**18), "ERC20 allowance too small" ); require(getReserves().contains(tokenId), "Not in holdings"); getERC20().burnFrom(to, 10**18); getReserves().remove(tokenId); if (!toSelf) { getCPM().transferPunk(to, tokenId); } emit DirectRedemption(tokenId, _msgSender(), to); } } contract Randomizable is Controllable { uint256 private randNonce = 0; function getPseudoRand(uint256 modulus) internal returns (uint256) { randNonce = randNonce.add(1); return uint256(keccak256(abi.encodePacked(now, _msgSender(), randNonce))) % modulus; } } contract Manageable is Randomizable { event MigrationComplete(address to); event TokenNameChange(string name); event TokenSymbolChange(string symbol); function migrate(address to, uint256 max) public onlyOwner whenNotLockedL { uint256 count = 0; uint256 reservesLength = getReserves().length(); for (uint256 i = 0; i < reservesLength; i++) { if (count >= max) { return; } uint256 tokenId = getReserves().at(0); getCPM().transferPunk(to, tokenId); getReserves().remove(tokenId); count = count.add(1); } getERC20().transferOwnership(to); emit MigrationComplete(to); } function changeTokenName(string memory newName) public onlyOwner whenNotLockedM { getERC20().changeName(newName); emit TokenNameChange(newName); } function changeTokenSymbol(string memory newSymbol) public onlyOwner whenNotLockedM { getERC20().changeSymbol(newSymbol); emit TokenSymbolChange(newSymbol); } function setReverseLink() public onlyOwner { getERC20().setVaultAddress(address(this)); } } contract PunkVault is Manageable { event TokenMinted(uint256 tokenId, address indexed to); event TokensMinted(uint256[] tokenIds, address indexed to); event TokenBurned(uint256 tokenId, address indexed to); event TokensBurned(uint256[] tokenIds, address indexed to); constructor(address erc20Address, address cpmAddress) public { setERC20Address(erc20Address); setCpmAddress(cpmAddress); } function getCryptoPunkAtIndex(uint256 index) public view returns (uint256) { return getReserves().at(index); } function getReservesLength() public view returns (uint256) { return getReserves().length(); } function isCryptoPunkDeposited(uint256 tokenId) public view returns (bool) { return getReserves().contains(tokenId); } function mintPunk(uint256 tokenId) public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getMintFees()); uint256 bounty = getMintBounty(1); if (fee > bounty) { uint256 differnce = fee.sub(bounty); require(msg.value >= differnce, "Value too low"); } bool success = _mintPunk(tokenId, false); if (success && bounty > fee) { uint256 difference = bounty.sub(fee); uint256 balance = address(this).balance; address payable sender = _msgSender(); if (balance >= difference) { sender.transfer(difference); } else { sender.transfer(balance); } } } function _mintPunk(uint256 tokenId, bool partOfDualOp) private returns (bool) { address msgSender = _msgSender(); require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); require(_tokenId == tokenId, "Wrong punk"); require(forSale, "Punk not available"); require(buyer == address(this), "Transfer not approved"); require(minVal == 0, "Min value not zero"); require(msgSender == seller, "Sender is not seller"); require( msgSender == getCPM().punkIndexToAddress(tokenId), "Sender is not owner" ); getCPM().buyPunk(tokenId); getReserves().add(tokenId); if (!partOfDualOp) { uint256 tokenAmount = 10**18; getERC20().mint(msgSender, tokenAmount); } emit TokenMinted(tokenId, _msgSender()); return true; } function mintPunkMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), tokenIds.length, _getMintFees()); uint256 bounty = getMintBounty(tokenIds.length); require(bounty >= fee || msg.value >= fee.sub(bounty), "Value too low"); uint256 numTokens = _mintPunkMultiple(tokenIds, false); require(numTokens > 0, "No tokens minted"); require(numTokens == tokenIds.length, "Untransferable punks"); if (fee > bounty) { uint256 differnce = fee.sub(bounty); require(msg.value >= differnce, "Value too low"); } if (bounty > fee) { uint256 difference = bounty.sub(fee); uint256 balance = address(this).balance; address payable sender = _msgSender(); if (balance >= difference) { sender.transfer(difference); } else { sender.transfer(balance); } } } function _mintPunkMultiple(uint256[] memory tokenIds, bool partOfDualOp) private returns (uint256) { require(tokenIds.length > 0, "No tokens"); require(tokenIds.length <= 100, "Over 100 tokens"); uint256[] memory newTokenIds = new uint256[](tokenIds.length); uint256 numNewTokens = 0; address msgSender = _msgSender(); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); bool rightToken = _tokenId == tokenId; bool isApproved = buyer == address(this); bool priceIsZero = minVal == 0; bool isSeller = msgSender == seller; bool isOwner = msgSender == getCPM().punkIndexToAddress(tokenId); if ( forSale && rightToken && isApproved && priceIsZero && isSeller && isOwner ) { getCPM().buyPunk(tokenId); getReserves().add(tokenId); newTokenIds[numNewTokens] = tokenId; numNewTokens = numNewTokens.add(1); } } if (numNewTokens > 0) { if (!partOfDualOp) { uint256 tokenAmount = numNewTokens * (10**18); getERC20().mint(msgSender, tokenAmount); } emit TokensMinted(newTokenIds, msgSender); } return numNewTokens; } function redeemPunk() public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getBurnFees()) + getBurnBounty(1); require(msg.value >= fee, "Value too low"); _redeemPunk(false); } function _redeemPunk(bool partOfDualOp) private { address msgSender = _msgSender(); uint256 tokenAmount = 10**18; require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); emit TokenBurned(tokenId, msgSender); } function redeemPunkMultiple(uint256 numTokens) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), numTokens, _getBurnFees()) + getBurnBounty(numTokens); require(msg.value >= fee, "Value too low"); _redeemPunkMultiple(numTokens, false); } function _redeemPunkMultiple(uint256 numTokens, bool partOfDualOp) private { require(numTokens > 0, "No tokens"); require(numTokens <= 100, "Over 100 tokens"); address msgSender = _msgSender(); uint256 tokenAmount = numTokens * (10**18); require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } uint256[] memory tokenIds = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); tokenIds[i] = tokenId; getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); } emit TokensBurned(tokenIds, msgSender); } function mintAndRedeem(uint256 tokenId) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), 1, _getDualFees()); require(msg.value >= fee, "Value too low"); require(_mintPunk(tokenId, true), "Minting failed"); _redeemPunk(true); } function mintAndRedeemMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 numTokens = tokenIds.length; require(numTokens > 0, "No tokens"); require(numTokens <= 20, "Over 20 tokens"); uint256 fee = getFee(_msgSender(), numTokens, _getDualFees()); require(msg.value >= fee, "Value too low"); uint256 numTokensMinted = _mintPunkMultiple(tokenIds, true); if (numTokensMinted > 0) { _redeemPunkMultiple(numTokens, true); } } function mintRetroactively(uint256 tokenId, address to) public onlyOwner whenNotLockedS { require( getCPM().punkIndexToAddress(tokenId) == address(this), "Not owner" ); require(!getReserves().contains(tokenId), "Already in reserves"); uint256 cryptoPunkBalance = getCPM().balanceOf(address(this)); require( (getERC20().totalSupply() / (10**18)) < cryptoPunkBalance, "No excess NFTs" ); getReserves().add(tokenId); getERC20().mint(to, 10**18); emit TokenMinted(tokenId, _msgSender()); } function redeemRetroactively(address to) public onlyOwner whenNotLockedS { require( getERC20().balanceOf(address(this)) >= (10**18), "Not enough PUNK" ); getERC20().burn(10**18); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); getReserves().remove(tokenId); getCPM().transferPunk(to, tokenId); emit TokenBurned(tokenId, _msgSender()); } }
0x6080604052600436106102ae5760003560e01c806397a6d27411610175578063c73cce39116100dc578063f2a6f21511610095578063fa70c3021161006f578063fa70c30214610d53578063fb15298d14610ddd578063fb34499d14610e16578063fc9d015414610e43576102ae565b8063f2a6f21514610cf6578063f2fde38b14610d0b578063f338fc1914610d3e576102ae565b8063c73cce3914610a6e578063cf43cd6d14610b1c578063cf97174814610bca578063e0dba60f14610c6b578063e63b094014610ca6578063f055c9a014610cbb576102ae565b8063ad68ebf71161012e578063ad68ebf714610876578063b0018bfc146108af578063b429afeb14610960578063b9f890de14610993578063c2c0d418146109a8578063c6d3ab9d146109bd576102ae565b806397a6d274146107215780639cd7d766146107545780639f3d4e69146108025780639f92b09b1461082f578063a2be5a1f14610859578063a70e81fd14610861576102ae565b8063715018a611610219578063830ddb97116101d2578063830ddb97146105c85780638456cb59146105e557806386a206e4146105fa5780638985a3f01461062b57806389caf16d146106d95780638da5cb5b1461070c576102ae565b8063715018a6146104f257806372e0dbd41461050757806372f9c421146105245780637af9bc02146105515780637fc72e7514610566578063824580b31461058f576102ae565b80633f4ba83a1161026b5780633f4ba83a1461044e5780634ad4f87c1461046357806350018eff1461047857806351cff8d91461048d5780635395b702146104c05780635ea0fa04146104d5576102ae565b80630bdf02bd146102b35780632361741e146102f25780632753167b1461035757806331f8a39d1461036c57806334d9d89c1461040f5780633e8354f014610439575b600080fd5b3480156102bf57600080fd5b506102e0600480360360208110156102d657600080fd5b503560ff16610e58565b60408051918252519081900360200190f35b3480156102fe57600080fd5b50610307610e8c565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561034357818101518382015260200161032b565b505050509050019250505060405180910390f35b34801561036357600080fd5b50610307610ee5565b61040d6004803603602081101561038257600080fd5b810190602081018135600160201b81111561039c57600080fd5b8201836020820111156103ae57600080fd5b803590602001918460208302840111600160201b831117156103cf57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550610f3b945050505050565b005b34801561041b57600080fd5b506102e06004803603602081101561043257600080fd5b5035611271565b34801561044557600080fd5b5061040d611291565b34801561045a57600080fd5b5061040d611339565b34801561046f57600080fd5b506102e06113a0565b34801561048457600080fd5b506103076113a6565b34801561049957600080fd5b5061040d600480360360208110156104b057600080fd5b50356001600160a01b03166113fc565b3480156104cc57600080fd5b506102e061156e565b61040d600480360360208110156104eb57600080fd5b5035611574565b3480156104fe57600080fd5b5061040d611724565b61040d6004803603602081101561051d57600080fd5b50356117c6565b34801561053057600080fd5b506102e06004803603602081101561054757600080fd5b503560ff1661192a565b34801561055d57600080fd5b5061040d611a0a565b34801561057257600080fd5b5061057b611dc5565b604080519115158252519081900360200190f35b34801561059b57600080fd5b5061040d600480360360408110156105b257600080fd5b50803590602001356001600160a01b0316611dce565b61040d600480360360208110156105de57600080fd5b50356121cb565b3480156105f157600080fd5b5061040d612326565b34801561060657600080fd5b5061060f612393565b604080516001600160a01b039092168252519081900360200190f35b34801561063757600080fd5b5061040d6004803603602081101561064e57600080fd5b810190602081018135600160201b81111561066857600080fd5b82018360208201111561067a57600080fd5b803590602001918460208302840111600160201b8311171561069b57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506123a2945050505050565b3480156106e557600080fd5b5061040d600480360360208110156106fc57600080fd5b50356001600160a01b0316612564565b34801561071857600080fd5b5061060f6128b5565b34801561072d57600080fd5b5061057b6004803603602081101561074457600080fd5b50356001600160a01b03166128c4565b34801561076057600080fd5b5061040d6004803603602081101561077757600080fd5b810190602081018135600160201b81111561079157600080fd5b8201836020820111156107a357600080fd5b803590602001918460208302840111600160201b831117156107c457600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506128e2945050505050565b34801561080e57600080fd5b5061040d6004803603602081101561082557600080fd5b503560ff16612a99565b34801561083b57600080fd5b5061057b6004803603602081101561085257600080fd5b5035612b68565b61040d612b76565b34801561086d57600080fd5b5061040d612c90565b34801561088257600080fd5b5061040d6004803603604081101561089957600080fd5b506001600160a01b038135169060200135612d61565b3480156108bb57600080fd5b5061040d600480360360208110156108d257600080fd5b810190602081018135600160201b8111156108ec57600080fd5b8201836020820111156108fe57600080fd5b803590602001918460018302840111600160201b8311171561091f57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550613003945050505050565b34801561096c57600080fd5b5061057b6004803603602081101561098357600080fd5b50356001600160a01b0316613257565b34801561099f57600080fd5b5061060f613275565b3480156109b457600080fd5b506102e0613284565b3480156109c957600080fd5b5061040d600480360360208110156109e057600080fd5b810190602081018135600160201b8111156109fa57600080fd5b820183602082011115610a0c57600080fd5b803590602001918460018302840111600160201b83111715610a2d57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550613296945050505050565b348015610a7a57600080fd5b5061040d60048036036020811015610a9157600080fd5b810190602081018135600160201b811115610aab57600080fd5b820183602082011115610abd57600080fd5b803590602001918460208302840111600160201b83111715610ade57600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506134a8945050505050565b348015610b2857600080fd5b5061040d60048036036020811015610b3f57600080fd5b810190602081018135600160201b811115610b5957600080fd5b820183602082011115610b6b57600080fd5b803590602001918460208302840111600160201b83111715610b8c57600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061364d945050505050565b61040d60048036036020811015610be057600080fd5b810190602081018135600160201b811115610bfa57600080fd5b820183602082011115610c0c57600080fd5b803590602001918460208302840111600160201b83111715610c2d57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550613804945050505050565b348015610c7757600080fd5b5061040d60048036036040811015610c8e57600080fd5b506001600160a01b03813516906020013515156139fa565b348015610cb257600080fd5b5061040d613bd0565b348015610cc757600080fd5b5061040d60048036036040811015610cde57600080fd5b506001600160a01b0381351690602001351515613c34565b348015610d0257600080fd5b5061057b613e25565b348015610d1757600080fd5b5061040d60048036036020811015610d2e57600080fd5b50356001600160a01b0316613e35565b348015610d4a57600080fd5b50610307613f2d565b348015610d5f57600080fd5b50610d68613f83565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610da2578181015183820152602001610d8a565b50505050905090810190601f168015610dcf5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610de957600080fd5b5061040d60048036036040811015610e0057600080fd5b50803590602001356001600160a01b031661402e565b348015610e2257600080fd5b5061040d60048036036020811015610e3957600080fd5b503560ff16614482565b348015610e4f57600080fd5b5061040d614576565b6000600a6000836002811115610e6a57fe5b6002811115610e7557fe5b81526020019081526020016000205490505b919050565b6060600e805480602002602001604051908101604052809291908181526020018280548015610eda57602002820191906000526020600020905b815481526020019060010190808311610ec6575b505050505090505b90565b6060600f805480602002602001604051908101604052809291908181526020018280548015610eda5760200282019190600052602060002090815481526020019060010190808311610ec6575050505050905090565b60026005541415610f81576040805162461bcd60e51b815260206004820152601f6024820152600080516020615cf8833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615610fda576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff161561102d576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b600061104961103a6145dd565b83516110446145e1565b6145e6565b90506000611057835161467b565b905081811015806110775750611073828263ffffffff61470116565b3410155b6110b8576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b60006110c5846000614743565b90506000811161110f576040805162461bcd60e51b815260206004820152601060248201526f139bc81d1bdad95b9cc81b5a5b9d195960821b604482015290519081900360640190fd5b8351811461115b576040805162461bcd60e51b8152602060048201526014602482015273556e7472616e7366657261626c652070756e6b7360601b604482015290519081900360640190fd5b818311156111be576000611175848463ffffffff61470116565b9050803410156111bc576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b505b828211156112665760006111d8838563ffffffff61470116565b90504760006111e56145dd565b905082821061122a576040516001600160a01b0382169084156108fc029085906000818181858888f19350505050158015611224573d6000803e3d6000fd5b50611262565b6040516001600160a01b0382169083156108fc029084906000818181858888f19350505050158015611260573d6000803e3d6000fd5b505b5050505b505060016005555050565b600061128b8261127f614be3565b9063ffffffff614be816565b92915050565b6112996145dd565b6000546001600160a01b039081169116146112e9576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b60036009541061132e576040805162461bcd60e51b815260206004820152600b60248201526a082d8e4cac2c8f240dac2f60ab1b604482015290519081900360640190fd5b600980546001019055565b6113416145dd565b6000546001600160a01b03908116911614611391576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6000805460ff60a01b19169055565b600c5490565b60606010805480602002602001604051908101604052809291908181526020018280548015610eda5760200282019190600052602060002090815481526020019060010190808311610ec6575050505050905090565b6114046145dd565b6000546001600160a01b03908116911614611454576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615d5e83398151915254806114a9576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116114ec576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b60405147906001600160a01b0384169082156108fc029083906000818181858888f19350505050158015611524573d6000803e3d6000fd5b50604080516001600160a01b03851681526020810183905281517f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65929181900390910190a1505050565b60125490565b600260055414156115ba576040805162461bcd60e51b815260206004820152601f6024820152600080516020615cf8833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615611613576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff1615611666576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b600061167d6116736145dd565b6001611044614bf4565b9050803410156116c4576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b6116cf826001614bf9565b611711576040805162461bcd60e51b815260206004820152600e60248201526d135a5b9d1a5b99c819985a5b195960921b604482015290519081900360640190fd5b61171b600161509b565b50506001600555565b61172c6145dd565b6000546001600160a01b0390811691161461177c576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6002600554141561180c576040805162461bcd60e51b815260206004820152601f6024820152600080516020615cf8833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615611865576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff16156118b8576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b60006118c3826153f0565b6118d76118ce6145dd565b8461104461547b565b0190508034101561191f576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b61171b826000615480565b60006009546000141561193f57506002610e87565b600082600281111561194d57fe5b141561198e576009546001141561196f576119686001615919565b9050610e87565b60095460021415611984576119686002615919565b6119686003615919565b600182600281111561199c57fe5b14156119d657600954600114156119b7576119686002615919565b600954600214156119cc576119686003615919565b6119686005615919565b600954600114156119eb576119686003615919565b60095460021415611a00576119686005615919565b611968600a615919565b600054600160a01b900460ff16611a61576040805162461bcd60e51b815260206004820152601660248201527510dbdb9d1c9858dd081a5cc81b9bdd081c185d5cd95960521b604482015290519081900360640190fd5b60026005541415611aa7576040805162461bcd60e51b815260206004820152601f6024820152600080516020615cf8833981519152604482015290519081900360640190fd5b6002600555670de0b6b3a7640000611abd615921565b6001600160a01b03166370a08231336040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015611b1257600080fd5b505afa158015611b26573d6000803e3d6000fd5b505050506040513d6020811015611b3c57600080fd5b50511015611b8b576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b670de0b6b3a7640000611b9c615921565b60408051636eb1769f60e11b815233600482015230602482015290516001600160a01b03929092169163dd62ed3e91604480820192602092909190829003018186803b158015611beb57600080fd5b505afa158015611bff573d6000803e3d6000fd5b505050506040513d6020811015611c1557600080fd5b50511015611c66576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b6000611c7960068263ffffffff614be816565b9050611c83615921565b6040805163079cc67960e41b8152336004820152670de0b6b3a7640000602482015290516001600160a01b0392909216916379cc67909160448082019260009290919082900301818387803b158015611cdb57600080fd5b505af1158015611cef573d6000803e3d6000fd5b50505050611d0781600661593090919063ffffffff16565b50611d1061593c565b6001600160a01b0316638b72a2ec33836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015611d6f57600080fd5b505af1158015611d83573d6000803e3d6000fd5b50506040805184815290513393507f8b309647fdd65a5ccf8e22445d08d0c72aca99f0674013717bb2fde8d64709ae92509081900360200190a2506001600555565b60085460ff1690565b611dde611dd96145dd565b613257565b611e22576040805162461bcd60e51b815260206004820152601060248201526f2737ba10309031b7b73a3937b63632b960811b604482015290519081900360640190fd5b670de0b6b3a7640000611e33615921565b6001600160a01b03166370a08231836040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015611e8857600080fd5b505afa158015611e9c573d6000803e3d6000fd5b505050506040513d6020811015611eb257600080fd5b50511015611f01576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b6001600160a01b03811630148080611fa55750670de0b6b3a7640000611f25615921565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b158015611f7657600080fd5b505afa158015611f8a573d6000803e3d6000fd5b505050506040513d6020811015611fa057600080fd5b505110155b611ff2576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b61200a83611ffe614be3565b9063ffffffff61594b16565b61204d576040805162461bcd60e51b815260206004820152600f60248201526e4e6f7420696e20686f6c64696e677360881b604482015290519081900360640190fd5b612055615921565b6001600160a01b03166379cc679083670de0b6b3a76400006040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156120bc57600080fd5b505af11580156120d0573d6000803e3d6000fd5b505050506120ec836120e0614be3565b9063ffffffff61593016565b5080612172576120fa61593c565b6001600160a01b0316638b72a2ec83856040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561215957600080fd5b505af115801561216d573d6000803e3d6000fd5b505050505b816001600160a01b03167f797bd1463a543a5fb696ff9b9d3340b0bef8762932107d896f055b77e4d93d4b846121a66145dd565b604080519283526001600160a01b0390911660208301528051918290030190a2505050565b60026005541415612211576040805162461bcd60e51b815260206004820152601f6024820152600080516020615cf8833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff161561226a576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60006122816122776145dd565b60016110446145e1565b9050600061228f600161467b565b9050808211156122f45760006122ab838363ffffffff61470116565b9050803410156122f2576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b505b6000612301846000614bf9565b905080801561230f57508282115b156112665760006111d8838563ffffffff61470116565b61232e6145dd565b6000546001600160a01b0390811691161461237e576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6000805460ff60a01b1916600160a01b179055565b6002546001600160a01b031690565b6123aa6145dd565b6000546001600160a01b039081169116146123fa576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615d5e833981519152548061244f576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612492576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b81516003146124d7576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b81516124ea90600f906020850190615c70565b507f556290bdbad25e439ee0740de619ad1d21a711a9f3c21030bdaffbfb9b679e15826040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561254d578181015183820152602001612535565b505050509050019250505060405180910390a15050565b61256c6145dd565b6000546001600160a01b039081169116146125bc576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b60008052600a6020527f13da86008ba1c6922daee3e07db95305ef49ebced9f5467a0b8613fcc6b343e35480612622576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612665576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b670de0b6b3a7640000612676615921565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b1580156126cb57600080fd5b505afa1580156126df573d6000803e3d6000fd5b505050506040513d60208110156126f557600080fd5b5051101561273c576040805162461bcd60e51b815260206004820152600f60248201526e4e6f7420656e6f7567682050554e4b60881b604482015290519081900360640190fd5b612744615921565b6001600160a01b03166342966c68670de0b6b3a76400006040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b15801561279157600080fd5b505af11580156127a5573d6000803e3d6000fd5b5050505060006127bb6127b6614be3565b615957565b905060006127c882615962565b905060006127d88261127f614be3565b90506127e6816120e0614be3565b506127ef61593c565b6001600160a01b0316638b72a2ec86836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561284e57600080fd5b505af1158015612862573d6000803e3d6000fd5b5050505061286e6145dd565b6001600160a01b03167f33631bcd0a4d34a7e2c240ab0753d5adfb7284d8ac89dab6876ec785c0cfa0e6826040518082815260200191505060405180910390a25050505050565b6000546001600160a01b031690565b6001600160a01b03166000908152600b602052604090205460ff1690565b6128ea6145dd565b6000546001600160a01b0390811691161461293a576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba854806129a1576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116129e4576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600214612a29576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b8151612a3c906010906020850190615c70565b5060408051602080825284518183015284517fbbfba7b79c4ec17454bfb989aaa624c5de83143861bb0c1139da4f3b4b0a9f0d9386939283929183019181860191028083836000831561254d578181015183820152602001612535565b612aa16145dd565b6000546001600160a01b03908116911614612af1576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6000600a6000836002811115612b0357fe5b6002811115612b0e57fe5b8152602001908152602001600020819055507feee8c9a7b7852b972adec4c62096923d399a82270752d09060dd7ad07f39e3f98160405180826002811115612b5257fe5b60ff16815260200191505060405180910390a150565b600061128b82611ffe614be3565b60026005541415612bbc576040805162461bcd60e51b815260206004820152601f6024820152600080516020615cf8833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615612c15576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b6000612c2160016153f0565b612c36612c2c6145dd565b600161104461547b565b01905080341015612c7e576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b612c88600061509b565b506001600555565b612c986145dd565b6000546001600160a01b03908116911614612ce8576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b612cf0615921565b6001600160a01b03166385535cc5306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050600060405180830381600087803b158015612d4757600080fd5b505af1158015612d5b573d6000803e3d6000fd5b50505050565b612d696145dd565b6000546001600160a01b03908116911614612db9576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba85480612e20576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612e63576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b600080612e716127b6614be3565b905060005b81811015612f4657848310612e8d57505050612ffe565b6000612e9c600061127f614be3565b9050612ea661593c565b6001600160a01b0316638b72a2ec88836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015612f0557600080fd5b505af1158015612f19573d6000803e3d6000fd5b50505050612f29816120e0614be3565b50612f3b84600163ffffffff6159e316565b935050600101612e76565b50612f4f615921565b6001600160a01b031663f2fde38b866040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050600060405180830381600087803b158015612fa657600080fd5b505af1158015612fba573d6000803e3d6000fd5b5050604080516001600160a01b038916815290517f6bc1a05a654a49243059be717e63e5e5a88fbb66af7093577daf9a27390722d19350908190036020019150a150505b505050565b61300b6145dd565b6000546001600160a01b0390811691161461305b576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615d5e83398151915254806130b0576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116130f3576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6130fb615921565b6001600160a01b0316635353a2d8836040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561315657818101518382015260200161313e565b50505050905090810190601f1680156131835780820380516001836020036101000a031916815260200191505b5092505050600060405180830381600087803b1580156131a257600080fd5b505af11580156131b6573d6000803e3d6000fd5b505050507f67c5eb670df7ec2c03a007ee155f462522e530d090c943b70c4eaa5656e0b7c6826040518080602001828103825283818151815260200191508051906020019080838360005b83811015613219578181015183820152602001613201565b50505050905090810190601f1680156132465780820380516001836020036101000a031916815260200191505b509250505060405180910390a15050565b6001600160a01b031660009081526011602052604090205460ff1690565b6001546001600160a01b031690565b60006132916127b6614be3565b905090565b61329e6145dd565b6000546001600160a01b039081169116146132ee576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615d5e8339815191525480613343576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613386576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b61338e615921565b6001600160a01b031663a3895fff836040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156133e95781810151838201526020016133d1565b50505050905090810190601f1680156134165780820380516001836020036101000a031916815260200191505b5092505050600060405180830381600087803b15801561343557600080fd5b505af1158015613449573d6000803e3d6000fd5b505060408051602080825286518183015286517f773ec0a6b643b90e0a49ac87584faa630abb0d1fa9bfe5d589918b6e33afbacf9550879450919283929083019185019080838360008315613219578181015183820152602001613201565b6134b06145dd565b6000546001600160a01b03908116911614613500576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615d5e8339815191525480613555576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613598576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b81516003146135dd576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b81516135f090600d906020850190615c70565b5060408051602080825284518183015284517ff9a8325633515ac20c4c12c09c48b1655bbe4a70f5ac29bd1f85803ef8a3be359386939283929183019181860191028083836000831561254d578181015183820152602001612535565b6136556145dd565b6000546001600160a01b039081169116146136a5576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba8548061370c576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b80421161374f576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600314613794576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b81516137a790600e906020850190615c70565b5060408051602080825284518183015284517fb1aecf0a8e6c83b5d243952384b0db2688bccb20ac76e4ced69a1e13f6a73d2f9386939283929183019181860191028083836000831561254d578181015183820152602001612535565b6002600554141561384a576040805162461bcd60e51b815260206004820152601f6024820152600080516020615cf8833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff16156138a3576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff16156138f6576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b805180613936576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b601481111561397d576040805162461bcd60e51b815260206004820152600e60248201526d4f76657220323020746f6b656e7360901b604482015290519081900360640190fd5b600061399361398a6145dd565b83611044614bf4565b9050803410156139da576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b60006139e7846001614743565b9050801561126657611266836001615480565b613a026145dd565b6000546001600160a01b03908116911614613a52576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615d5e8339815191525480613aa7576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613aea576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6001600160a01b03831660009081526011602052604090205460ff1615158215151415613b4c576040805162461bcd60e51b815260206004820152600b60248201526a105b1c9958591e481cd95d60aa1b604482015290519081900360640190fd5b8115613b6057601280546001019055613b6b565b601280546000190190555b6001600160a01b038316600081815260116020908152604091829020805460ff191686151590811790915582519384529083015280517f9c1e55b2ea976b1ce106746d9325847e838c89adca542764df43b80cadb59b049281900390910190a1505050565b613bd86145dd565b6000546001600160a01b03908116911614613c28576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6008805460ff19169055565b613c3c6145dd565b6000546001600160a01b03908116911614613c8c576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615d5e8339815191525480613ce1576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613d24576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6001600160a01b0383166000908152600b602052604090205460ff1615158215151415613d86576040805162461bcd60e51b815260206004820152600b60248201526a105b1c9958591e481cd95d60aa1b604482015290519081900360640190fd5b8115613da857600c54613da090600163ffffffff6159e316565b600c55613dc0565b600c54613dbc90600163ffffffff61470116565b600c555b6001600160a01b0383166000818152600b6020908152604091829020805460ff191686151590811790915582519384529083015280517f99042b85468bcc9210d26d97ff0ec84ccc48b4bc7dc16f8bc4a35c3d769cad939281900390910190a1505050565b600054600160a01b900460ff1690565b613e3d6145dd565b6000546001600160a01b03908116911614613e8d576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6001600160a01b038116613ed25760405162461bcd60e51b8152600401808060200182810382526026815260200180615d186026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b6060600d805480602002602001604051908101604052809291908181526020018280548015610eda5760200282019190600052602060002090815481526020019060010190808311610ec6575050505050905090565b606060095460001415613fb057506040805180820190915260038152621c995960ea1b6020820152610ee2565b60095460011415613fde57506040805180820190915260068152656f72616e676560d01b6020820152610ee2565b6009546002141561400c575060408051808201909152600681526579656c6c6f7760d01b6020820152610ee2565b5060408051808201909152600581526433b932b2b760d91b6020820152610ee2565b6140366145dd565b6000546001600160a01b03908116911614614086576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b60008052600a6020527f13da86008ba1c6922daee3e07db95305ef49ebced9f5467a0b8613fcc6b343e354806140ec576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b80421161412f576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b3061413861593c565b6001600160a01b03166358178168856040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561417d57600080fd5b505af1158015614191573d6000803e3d6000fd5b505050506040513d60208110156141a757600080fd5b50516001600160a01b0316146141f0576040805162461bcd60e51b81526020600482015260096024820152682737ba1037bbb732b960b91b604482015290519081900360640190fd5b6141fc83611ffe614be3565b15614244576040805162461bcd60e51b8152602060048201526013602482015272416c726561647920696e20726573657276657360681b604482015290519081900360640190fd5b600061424e61593c565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050602060405180830381600087803b1580156142a557600080fd5b505af11580156142b9573d6000803e3d6000fd5b505050506040513d60208110156142cf57600080fd5b5051905080670de0b6b3a76400006142e5615921565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561431d57600080fd5b505afa158015614331573d6000803e3d6000fd5b505050506040513d602081101561434757600080fd5b50518161435057fe5b0410614394576040805162461bcd60e51b815260206004820152600e60248201526d4e6f20657863657373204e46547360901b604482015290519081900360640190fd5b6143ac846143a0614be3565b9063ffffffff615a3d16565b506143b5615921565b6001600160a01b03166340c10f1984670de0b6b3a76400006040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561441c57600080fd5b505af1158015614430573d6000803e3d6000fd5b5050505061443c6145dd565b6001600160a01b03167f3a5398bda6f1f57d6c96834fa9bf02b5517bdc847d14312015a917ba421c31c9856040518082815260200191505060405180910390a250505050565b61448a6145dd565b6000546001600160a01b039081169116146144da576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b60006144f56144e88361192a565b429063ffffffff6159e316565b905080600a600084600281111561450857fe5b600281111561451357fe5b8152602001908152602001600020819055507f6e57d96ae65caee513bb2adf8adff1ea16e6bb5a6154e6939c8692392c576b6682826040518083600281111561455857fe5b60ff1681526020018281526020019250505060405180910390a15050565b61457e6145dd565b6000546001600160a01b039081169116146145ce576040805162461bcd60e51b81526020600482018190526024820152600080516020615d3e833981519152604482015290519081900360640190fd5b6008805460ff19166001179055565b3390565b600d90565b6001600160a01b0383166000908152600b6020526040812054819060ff1615614613576000915050614674565b836001141561463b578260008154811061462957fe5b90600052602060002001549050614671565b8260028154811061464857fe5b906000526020600020015484028360018154811061466257fe5b90600052602060002001540190505b90505b9392505050565b6000808061468a6127b6614be3565b90506000601060018154811061469c57fe5b906000526020600020015490508082116146f8576000805b868110156146f15782818501116146e957808401830360106000815481106146d857fe5b906000526020600020015402820191505b6001016146b4565b5092909201915b50909392505050565b600061467483836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250615a49565b600080835111614786576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b6064835111156147cf576040805162461bcd60e51b815260206004820152600f60248201526e4f7665722031303020746f6b656e7360881b604482015290519081900360640190fd5b6060835167ffffffffffffffff811180156147e957600080fd5b50604051908082528060200260200182016040528015614813578160200160208202803683370190505b5090506000806148216145dd565b905060005b8651811015614ac257600087828151811061483d57fe5b602002602001015190506127108110614890576040805162461bcd60e51b815260206004820152601060248201526f0e8ded6cadc92c840e8dede40d0d2ced60831b604482015290519081900360640190fd5b60008060008060006148a061593c565b6001600160a01b031663088f11f3876040518263ffffffff1660e01b81526004018082815260200191505060a060405180830381600087803b1580156148e557600080fd5b505af11580156148f9573d6000803e3d6000fd5b505050506040513d60a081101561490f57600080fd5b508051602082015160408301516060840151608090940151929850909650945090925090508584146001600160a01b038083163014908415908b811690871614600061495961593c565b6001600160a01b031663581781688c6040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561499e57600080fd5b505af11580156149b2573d6000803e3d6000fd5b505050506040513d60208110156149c857600080fd5b50516001600160a01b038e811691161490508980156149e45750845b80156149ed5750835b80156149f65750825b80156149ff5750815b8015614a085750805b15614aab57614a1561593c565b6001600160a01b0316638264fe988c6040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b158015614a5a57600080fd5b505af1158015614a6e573d6000803e3d6000fd5b50505050614a7e8b6143a0614be3565b508a8f8f81518110614a8c57fe5b6020908102919091010152614aa88e600163ffffffff6159e316565b9d505b505060019099019850614826975050505050505050565b508115614bda5784614b5a57670de0b6b3a76400008202614ae1615921565b6001600160a01b03166340c10f1983836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015614b4057600080fd5b505af1158015614b54573d6000803e3d6000fd5b50505050505b806001600160a01b03167fbc07a750767f513de2b3356e24037db0e90c9e5cdaa0d757c7e628c3d82e8f12846040518080602001828103825283818151815260200191508051906020019060200280838360005b83811015614bc6578181015183820152602001614bae565b505050509050019250505060405180910390a25b50949350505050565b600690565b60006146748383615ae0565b600f90565b600080614c046145dd565b90506127108410614c4f576040805162461bcd60e51b815260206004820152601060248201526f0e8ded6cadc92c840e8dede40d0d2ced60831b604482015290519081900360640190fd5b6000806000806000614c5f61593c565b6001600160a01b031663088f11f38a6040518263ffffffff1660e01b81526004018082815260200191505060a060405180830381600087803b158015614ca457600080fd5b505af1158015614cb8573d6000803e3d6000fd5b505050506040513d60a0811015614cce57600080fd5b50805160208201516040830151606084015160809094015192985090965094509092509050888414614d34576040805162461bcd60e51b815260206004820152600a60248201526957726f6e672070756e6b60b01b604482015290519081900360640190fd5b84614d7b576040805162461bcd60e51b815260206004820152601260248201527150756e6b206e6f7420617661696c61626c6560701b604482015290519081900360640190fd5b6001600160a01b0381163014614dd0576040805162461bcd60e51b8152602060048201526015602482015274151c985b9cd9995c881b9bdd08185c1c1c9bdd9959605a1b604482015290519081900360640190fd5b8115614e18576040805162461bcd60e51b81526020600482015260126024820152714d696e2076616c7565206e6f74207a65726f60701b604482015290519081900360640190fd5b826001600160a01b0316866001600160a01b031614614e75576040805162461bcd60e51b815260206004820152601460248201527329b2b73232b91034b9903737ba1039b2b63632b960611b604482015290519081900360640190fd5b614e7d61593c565b6001600160a01b031663581781688a6040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b158015614ec257600080fd5b505af1158015614ed6573d6000803e3d6000fd5b505050506040513d6020811015614eec57600080fd5b50516001600160a01b03878116911614614f43576040805162461bcd60e51b815260206004820152601360248201527229b2b73232b91034b9903737ba1037bbb732b960691b604482015290519081900360640190fd5b614f4b61593c565b6001600160a01b0316638264fe988a6040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b158015614f9057600080fd5b505af1158015614fa4573d6000803e3d6000fd5b50505050614fb4896143a0614be3565b508761504457670de0b6b3a7640000614fcb615921565b6001600160a01b03166340c10f1988836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561502a57600080fd5b505af115801561503e573d6000803e3d6000fd5b50505050505b61504c6145dd565b6001600160a01b03167f3a5398bda6f1f57d6c96834fa9bf02b5517bdc847d14312015a917ba421c31c98a6040518082815260200191505060405180910390a250600198975050505050505050565b60006150a56145dd565b9050670de0b6b3a764000082806151445750806150c0615921565b6001600160a01b03166370a08231846040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561511557600080fd5b505afa158015615129573d6000803e3d6000fd5b505050506040513d602081101561513f57600080fd5b505110155b61518f576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b828061521f57508061519f615921565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b1580156151f057600080fd5b505afa158015615204573d6000803e3d6000fd5b505050506040513d602081101561521a57600080fd5b505110155b61526c576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b60006152796127b6614be3565b9050600061528682615962565b905060006152968261127f614be3565b90508561531d576152a5615921565b6001600160a01b03166379cc679086866040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561530457600080fd5b505af1158015615318573d6000803e3d6000fd5b505050505b615329816120e0614be3565b5061533261593c565b6001600160a01b0316638b72a2ec86836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561539157600080fd5b505af11580156153a5573d6000803e3d6000fd5b50506040805184815290516001600160a01b03891693507f33631bcd0a4d34a7e2c240ab0753d5adfb7284d8ac89dab6876ec785c0cfa0e692509081900360200190a2505050505050565b600080806153ff6127b6614be3565b90506000601060018154811061541157fe5b9060005260206000200154905080858303116146f8576000805b868110156146f157828185031115801561544757506000818503115b15615473578084038303600101601060008154811061546257fe5b906000526020600020015402820191505b60010161542b565b600e90565b600082116154c1576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b6064821115615509576040805162461bcd60e51b815260206004820152600f60248201526e4f7665722031303020746f6b656e7360881b604482015290519081900360640190fd5b60006155136145dd565b9050670de0b6b3a7640000830282806155b4575080615530615921565b6001600160a01b03166370a08231846040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561558557600080fd5b505afa158015615599573d6000803e3d6000fd5b505050506040513d60208110156155af57600080fd5b505110155b6155ff576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b828061568f57508061560f615921565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b15801561566057600080fd5b505afa158015615674573d6000803e3d6000fd5b505050506040513d602081101561568a57600080fd5b505110155b6156dc576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b82615761576156e9615921565b6001600160a01b03166379cc679083836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561574857600080fd5b505af115801561575c573d6000803e3d6000fd5b505050505b60608467ffffffffffffffff8111801561577a57600080fd5b506040519080825280602002602001820160405280156157a4578160200160208202803683370190505b50905060005b858110156158925760006157bf6127b6614be3565b905060006157cc82615962565b905060006157dc8261127f614be3565b9050808585815181106157eb57fe5b602002602001018181525050615803816120e0614be3565b5061580c61593c565b6001600160a01b0316638b72a2ec88836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561586b57600080fd5b505af115801561587f573d6000803e3d6000fd5b5050600190950194506157aa9350505050565b50826001600160a01b03167fbcf5ab3acba5a0c4486ea481f9aff9688ca72d992d52325968caafb9849d8b0a826040518080602001828103825283818151815260200191508051906020019060200280838360005b838110156158ff5781810151838201526020016158e7565b505050509050019250505060405180910390a25050505050565b620151800290565b6003546001600160a01b031690565b60006146748383615b44565b6004546001600160a01b031690565b60006146748383615c0a565b600061128b82615c22565b60135460009061597990600163ffffffff6159e316565b60135581426159866145dd565b60135460405160200180848152602001836001600160a01b03166001600160a01b031660601b815260140182815260200193505050506040516020818303038152906040528051906020012060001c816159dc57fe5b0692915050565b600082820183811015614674576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b60006146748383615c26565b60008184841115615ad85760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015615a9d578181015183820152602001615a85565b50505050905090810190601f168015615aca5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b81546000908210615b225760405162461bcd60e51b8152600401808060200182810382526022815260200180615cd66022913960400191505060405180910390fd5b826000018281548110615b3157fe5b9060005260206000200154905092915050565b60008181526001830160205260408120548015615c005783546000198083019190810190600090879083908110615b7757fe5b9060005260206000200154905080876000018481548110615b9457fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080615bc457fe5b6001900381819060005260206000200160009055905586600101600087815260200190815260200160002060009055600194505050505061128b565b600091505061128b565b60009081526001919091016020526040902054151590565b5490565b6000615c328383615c0a565b615c685750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561128b565b50600061128b565b828054828255906000526020600020908101928215615cab579160200282015b82811115615cab578251825591602001919060010190615c90565b50615cb7929150615cbb565b5090565b610ee291905b80821115615cb75760008155600101615cc156fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64735265656e7472616e637947756172643a207265656e7472616e742063616c6c004f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572bbc70db1b6c7afd11e79c0fb0051300458f1a3acb8ee9789d9b6b26c61ad9bc7a264697066735822122007d776808cbdbccdd39b799d472b98ed1fe5d36402d6c4523d7755b418e0a54664736f6c63430006080033
[ 10, 5, 11 ]
0x556148562d5ddeb72545d7ec4b3ec8edc8f55ba7
pragma solidity 0.7.1; 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"); } } abstract contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () { } 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; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface PRDX_staking { function stake(address staker, uint256 amount) external returns (bool success); } interface PRDX_prediction { function predict(address user, uint256 amount, uint256 price, uint256 phase) external returns (bool success); } interface PRDX_tokendistr { function sell_PRDX(address user, uint256 amount) external returns (bool success); } contract PredixNetwork is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; //contract addresses address public staking_addr ; address public prediction_addr ; address public tokendistr_addr ; //contracts PRDX_staking staking_contract = PRDX_staking(staking_addr) ; PRDX_prediction prediction_contract = PRDX_prediction(prediction_addr) ; PRDX_tokendistr tokendistr_contract = PRDX_tokendistr(tokendistr_addr) ; /** * @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 () { _name = "Predix Network"; _symbol = "PRDX"; _decimals = 18; _mint(msg.sender, 1.6 * 1e6 * 10**_decimals); } /** * @dev Set staking contract address * @param addr Address of staking contract * */ function set_staking_address(address addr) public onlyOwner { staking_addr = addr ; staking_contract = PRDX_staking(staking_addr) ; } /** * @dev Set prediction market contract address * @param addr Address of prediction market contract * */ function set_prediction_address(address addr) public onlyOwner { prediction_addr = addr ; prediction_contract = PRDX_prediction(prediction_addr) ; } function set_tokendistr_address(address addr) public onlyOwner { tokendistr_addr = addr ; tokendistr_contract = PRDX_tokendistr(tokendistr_addr) ; } /** * @dev Approve prediction market contract to take tokens and make prediction * @param amount Value of prediction paid by user * price Predicted price at phase close * phase Phase for which prediction is made * @return success Success of transaction, only false if transaction failed */ function approveAndPredict(uint256 amount, uint256 price, uint256 phase) public returns (bool success) { require(balanceOf(msg.sender) >= amount, "Prediction amount exceeds user token balance") ; _approve(msg.sender, prediction_addr, amount) ; require(prediction_contract.predict(msg.sender, amount, price, phase)) ; return true ; } /** * @dev Approve staking contract to take tokens and start staking * @param amount Amount of tokens to be staked * @return success Success of transaction, only false if transaction failed */ function approveAndStake(uint256 amount) public returns (bool success) { require(balanceOf(msg.sender) >= amount, "Staking amount exceeds user token balance") ; _approve(msg.sender, staking_addr, amount) ; require(staking_contract.stake(msg.sender, amount)) ; return true ; } /** * @dev Approve token distribution contract to take tokens and sell tokens for Ether * @param amount Amount of PRDX to sell * @return success Success of transaction, only false if transaction failed */ function approveAndSell(uint256 amount) public returns (bool success) { require(balanceOf(msg.sender) >= amount, "Sell amount exceeds user token balance") ; _approve(msg.sender, tokendistr_addr, amount) ; require(tokendistr_contract.sell_PRDX(msg.sender, amount)) ; return true ; } /** * @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)); 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)); 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); _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(uint256 amount) public { require(msg.sender != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(msg.sender, address(0), amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(msg.sender, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } }
0x608060405234801561001057600080fd5b50600436106101585760003560e01c80638da5cb5b116100c3578063d97261f81161007c578063d97261f8146106d2578063dd62ed3e14610716578063e26597751461078e578063ea33bfbd146107c2578063f2fde38b14610806578063f728b1d81461084a57610158565b80638da5cb5b146104e157806395d89b41146105155780639b1f9e7414610598578063a44d9410146105c6578063a457c2d71461060a578063a9059cbb1461066e57610158565b8063313ce56711610115578063313ce5671461035e578063395093511461037f57806361f4d4d3146103e35780636f55d4b41461043b57806370a082311461047f578063715018a6146104d757610158565b806306fdde031461015d578063095ea7b3146101e05780630fc583ed1461024457806317e202941461028857806318160ddd146102bc57806323b872dd146102da575b600080fd5b61016561087e565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101a557808201518184015260208101905061018a565b50505050905090810190601f1680156101d25780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61022c600480360360408110156101f657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610920565b60405180821515815260200191505060405180910390f35b6102866004803603602081101561025a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061093e565b005b610290610aad565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102c4610ad3565b6040518082815260200191505060405180910390f35b610346600480360360608110156102f057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610add565b60405180821515815260200191505060405180910390f35b610366610b9c565b604051808260ff16815260200191505060405180910390f35b6103cb6004803603604081101561039557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610bb3565b60405180821515815260200191505060405180910390f35b610423600480360360608110156103f957600080fd5b81019080803590602001909291908035906020019092919080359060200190929190505050610c66565b60405180821515815260200191505060405180910390f35b61047d6004803603602081101561045157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610de8565b005b6104c16004803603602081101561049557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610f57565b6040518082815260200191505060405180910390f35b6104df610fa0565b005b6104e9611126565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61051d61114f565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561055d578082015181840152602081019050610542565b50505050905090810190601f16801561058a5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6105c4600480360360208110156105ae57600080fd5b81019080803590602001909291905050506111f1565b005b6105f2600480360360208110156105dc57600080fd5b810190808035906020019092919050505061139c565b60405180821515815260200191505060405180910390f35b6106566004803603604081101561062057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061150c565b60405180821515815260200191505060405180910390f35b6106ba6004803603604081101561068457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506115bf565b60405180821515815260200191505060405180910390f35b610714600480360360208110156106e857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506115dd565b005b6107786004803603604081101561072c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061174c565b6040518082815260200191505060405180910390f35b6107966117d3565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6107ee600480360360208110156107d857600080fd5b81019080803590602001909291905050506117f9565b60405180821515815260200191505060405180910390f35b6108486004803603602081101561081c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611969565b005b610852611b74565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156109165780601f106108eb57610100808354040283529160200191610916565b820191906000526020600020905b8154815290600101906020018083116108f957829003601f168201915b5050505050905090565b600061093461092d611bb9565b8484611bc1565b6001905092915050565b610946611bb9565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610a06576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600760006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600a60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600860009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600354905090565b6000610aea848484611db8565b610b9184610af6611bb9565b610b8c85600260008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000610b43611bb9565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461206390919063ffffffff16565b611bc1565b600190509392505050565b6000600660009054906101000a900460ff16905090565b6000610c5c610bc0611bb9565b84610c578560026000610bd1611bb9565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611b9a90919063ffffffff16565b611bc1565b6001905092915050565b600083610c7233610f57565b1015610cc9576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c8152602001806120f4602c913960400191505060405180910390fd5b610cf633600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1686611bc1565b600a60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166304580319338686866040518563ffffffff1660e01b8152600401808573ffffffffffffffffffffffffffffffffffffffff168152602001848152602001838152602001828152602001945050505050602060405180830381600087803b158015610d9957600080fd5b505af1158015610dad573d6000803e3d6000fd5b505050506040513d6020811015610dc357600080fd5b8101908080519060200190929190505050610ddd57600080fd5b600190509392505050565b610df0611bb9565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610eb0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600860006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600860009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600b60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b610fa8611bb9565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611068576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a360008060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b606060058054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156111e75780601f106111bc576101008083540402835291602001916111e7565b820191906000526020600020905b8154815290600101906020018083116111ca57829003601f168201915b5050505050905090565b600073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415611277576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806121466021913960400191505060405180910390fd5b61128333600083612083565b6112d581600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461206390919063ffffffff16565b600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061132d8160035461206390919063ffffffff16565b600381905550600073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a350565b6000816113a833610f57565b10156113ff576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001806121206026913960400191505060405180910390fd5b61142c33600860009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1684611bc1565b600b60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663f27ce4ac33846040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156114bf57600080fd5b505af11580156114d3573d6000803e3d6000fd5b505050506040513d60208110156114e957600080fd5b810190808051906020019092919050505061150357600080fd5b60019050919050565b60006115b5611519611bb9565b846115b0856002600061152a611bb9565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461206390919063ffffffff16565b611bc1565b6001905092915050565b60006115d36115cc611bb9565b8484611db8565b6001905092915050565b6115e5611bb9565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146116a5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600660016101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff16600960006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600760009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60008161180533610f57565b101561185c576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260298152602001806121b06029913960400191505060405180910390fd5b61188933600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1684611bc1565b600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663adc9772e33846040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561191c57600080fd5b505af1158015611930573d6000803e3d6000fd5b505050506040513d602081101561194657600080fd5b810190808051906020019092919050505061196057600080fd5b60019050919050565b611971611bb9565b73ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611a31576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415611ab7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001806120ac6026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600080828401905083811015611baf57600080fd5b8091505092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611c47576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602481526020018061218c6024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611ccd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806120d26022913960400191505060405180910390fd5b80600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415611e3e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806121676025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611ec4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001806120896023913960400191505060405180910390fd5b611ecf838383612083565b611f2181600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461206390919063ffffffff16565b600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611fb681600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054611b9a90919063ffffffff16565b600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b60008282111561207257600080fd5b600082840390508091505092915050565b50505056fe45524332303a207472616e7366657220746f20746865207a65726f20616464726573734f776e61626c653a206e6577206f776e657220697320746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737350726564696374696f6e20616d6f756e742065786365656473207573657220746f6b656e2062616c616e636553656c6c20616d6f756e742065786365656473207573657220746f6b656e2062616c616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573735374616b696e6720616d6f756e742065786365656473207573657220746f6b656e2062616c616e6365a264697066735822122056436b34651b58b431590ef342f87909842ea1cda992ce74ff30a7810fbf007764736f6c63430007010033
[ 38 ]
0x5659668B6323eC0360fBDa5624B8247D443d3Dd9
pragma solidity 0.7.2; contract LYNCStakingV1 { //Enable SafeMath using SafeMath for uint256; address public owner; address public contractAddress; uint256 public totalRewards = 0; uint256 public totalRewardsClaimed = 0; uint256 public totalStakedV1 = 0; uint256 public oneDay = 86400; // in seconds uint256 public SCALAR = 1e18; // multiplier uint256 public minimumTokenStake = 98; // takes into account transfer fee uint256 public endOfStakeFee = 4; // 4% including 1% tx fee = approx 5% LYNCToken public tokenContract; //Events event Stake(address _from, uint256 tokens); event Unstake(address _to, uint256 tokens); event UnstakeFee(address _to, uint256 tokens); event CollectRewards(address _to, uint256 tokens); //User data struct Staker { uint256 staked; uint256 poolAtLastClaim; uint256 userTimeStamp; } //Mappings mapping(address => Staker) stakers; //On deployment constructor(LYNCToken _tokenContract) { owner = msg.sender; tokenContract = _tokenContract; contractAddress = address(this); } //MulDiv functions : source https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 function mulDiv(uint x, uint y, uint z) public pure returns (uint) { (uint l, uint h) = fullMul (x, y); assert (h < z); uint mm = mulmod(x, y, z); if (mm > l) h -= 1; l -= mm; uint pow2 = z & -z; z /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint r = 1; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; return l * r; } //Required for MulDiv function fullMul(uint x, uint y) private pure returns (uint l, uint h) { uint mm = mulmod(x, y, uint (-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } //Return current reward pool unclaimed function rewardPoolBalance() public view returns(uint256) { return tokenContract.balanceOf(address(this)).sub(totalStakedV1); } //Return staker information function stakerInformation(address _stakerAddress) public view returns(uint256, uint256, uint256) { return (stakers[_stakerAddress].staked, stakers[_stakerAddress].poolAtLastClaim, stakers[_stakerAddress].userTimeStamp); } //Stake tokens function stakeTokens(uint256 _numberOfTokens) external returns (bool) { //Check if user is already staking if(stakers[msg.sender].staked == 0) { //Require minimum stake require(_numberOfTokens > (minimumTokenStake * SCALAR), "Not enough tokens to start staking"); //Transfer tokens and update data require(tokenContract.transferFrom(msg.sender, address(this), _numberOfTokens)); stakers[msg.sender].poolAtLastClaim = totalRewards; stakers[msg.sender].userTimeStamp = block.timestamp; } else { //Transfer tokens require(tokenContract.transferFrom(msg.sender, address(this), _numberOfTokens)); } //Update staking totals uint256 _feeAmount = (_numberOfTokens.mul(tokenContract.feePercent())).div(100); uint256 _stakedAfterFee = _numberOfTokens.sub(_feeAmount); //Update data stakers[msg.sender].staked = (stakers[msg.sender].staked).add(_stakedAfterFee); totalStakedV1 = totalStakedV1.add(_stakedAfterFee); totalRewards = rewardPoolBalance().add(totalRewardsClaimed); emit Stake(msg.sender, _numberOfTokens); return true; } //Unstake tokens function unstakeTokens() external returns (bool) { //Minus 4% fee for unstaking uint256 _stakedTokens = stakers[msg.sender].staked; uint256 _feeAmount = (_stakedTokens.mul(endOfStakeFee)).div(100); uint256 _unstakeTokens = (stakers[msg.sender].staked).sub(_feeAmount); //Send stakers tokens and remove from total staked require(tokenContract.transfer(msg.sender, _unstakeTokens)); totalStakedV1 = totalStakedV1.sub(_stakedTokens); //Update data stakers[msg.sender].staked = 0; stakers[msg.sender].poolAtLastClaim = 0; stakers[msg.sender].userTimeStamp = 0; totalRewards = rewardPoolBalance().add(totalRewardsClaimed); emit Unstake(msg.sender, _unstakeTokens); emit UnstakeFee(msg.sender, _feeAmount); return true; } //Claim current token rewards function claimRewards() external returns (bool) { totalRewards = rewardPoolBalance().add(totalRewardsClaimed); require(stakers[msg.sender].staked > 0, "You do not have any tokens staked"); require(block.timestamp > (stakers[msg.sender].userTimeStamp + oneDay), "You can only claim 24 hours after staking and once every 24 hours"); //Calculated user share of reward pool since last claim uint256 _poolSinceLastClaim = totalRewards.sub(stakers[msg.sender].poolAtLastClaim); uint256 _rewardPercent = mulDiv(stakers[msg.sender].staked, 10000, totalStakedV1); uint256 _rewardToClaim = mulDiv(_poolSinceLastClaim, _rewardPercent, 10000); //Send tokens require(tokenContract.transfer(msg.sender, _rewardToClaim)); //Update data stakers[msg.sender].poolAtLastClaim = totalRewards; stakers[msg.sender].userTimeStamp = block.timestamp; totalRewardsClaimed = totalRewardsClaimed.add(_rewardToClaim); totalRewards = rewardPoolBalance().add(totalRewardsClaimed); emit CollectRewards(msg.sender, _rewardToClaim); return true; } //Update the minimum tokens to start staking function updateStakeMinimum(uint256 _minimumTokenStake) public onlyOwner { minimumTokenStake = _minimumTokenStake; } //Modifiers modifier onlyOwner() { require(owner == msg.sender, "Only current owner can call this function"); _; } } contract LYNCToken { //Enable SafeMath using SafeMath for uint256; //Token details string constant public name = "LYNC Network"; string constant public symbol = "LYNC"; uint8 constant public decimals = 18; //Reward pool and owner address address public owner; address public rewardPoolAddress; //Supply and tranasction fee uint256 public maxTokenSupply = 1e24; // 1,000,000 tokens uint256 public feePercent = 1; // initial transaction fee percentage uint256 public feePercentMax = 10; // maximum transaction fee percentage //Events event Transfer(address indexed _from, address indexed _to, uint256 _tokens); event Approval(address indexed _owner,address indexed _spender, uint256 _tokens); event TranserFee(uint256 _tokens); event UpdateFee(uint256 _fee); event RewardPoolUpdated(address indexed _rewardPoolAddress, address indexed _newRewardPoolAddress); event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner); event OwnershipRenounced(address indexed _previousOwner, address indexed _newOwner); //Mappings mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) private allowances; //On deployment constructor () { owner = msg.sender; rewardPoolAddress = address(this); balanceOf[msg.sender] = maxTokenSupply; emit Transfer(address(0), msg.sender, maxTokenSupply); } //ERC20 totalSupply function totalSupply() public view returns (uint256) { return maxTokenSupply; } //ERC20 transfer function transfer(address _to, uint256 _tokens) public returns (bool) { transferWithFee(msg.sender, _to, _tokens); return true; } //ERC20 transferFrom function transferFrom(address _from, address _to, uint256 _tokens) public returns (bool) { require(_tokens <= balanceOf[_from], "Not enough tokens in the approved address balance"); require(_tokens <= allowances[_from][msg.sender], "token amount is larger than the current allowance"); transferWithFee(_from, _to, _tokens); allowances[_from][msg.sender] = allowances[_from][msg.sender].sub(_tokens); return true; } //ERC20 approve function approve(address _spender, uint256 _tokens) public returns (bool) { allowances[msg.sender][_spender] = _tokens; emit Approval(msg.sender, _spender, _tokens); return true; } //ERC20 allowance function allowance(address _owner, address _spender) public view returns (uint256) { return allowances[_owner][_spender]; } //Transfer with transaction fee applied function transferWithFee(address _from, address _to, uint256 _tokens) internal returns (bool) { require(balanceOf[_from] >= _tokens, "Not enough tokens in the senders balance"); uint256 _feeAmount = (_tokens.mul(feePercent)).div(100); balanceOf[_from] = balanceOf[_from].sub(_tokens); balanceOf[_to] = balanceOf[_to].add(_tokens.sub(_feeAmount)); balanceOf[rewardPoolAddress] = balanceOf[rewardPoolAddress].add(_feeAmount); emit Transfer(_from, _to, _tokens.sub(_feeAmount)); emit Transfer(_from, rewardPoolAddress, _feeAmount); emit TranserFee(_tokens); return true; } //Update transaction fee percentage function updateFee(uint256 _updateFee) public onlyOwner { require(_updateFee <= feePercentMax, "Transaction fee cannot be greater than 10%"); feePercent = _updateFee; emit UpdateFee(_updateFee); } //Update the reward pool address function updateRewardPool(address _newRewardPoolAddress) public onlyOwner { require(_newRewardPoolAddress != address(0), "New reward pool address cannot be a zero address"); rewardPoolAddress = _newRewardPoolAddress; emit RewardPoolUpdated(rewardPoolAddress, _newRewardPoolAddress); } //Transfer current token balance to the reward pool address function rewardPoolBalanceTransfer() public onlyOwner returns (bool) { uint256 _currentBalance = balanceOf[address(this)]; transferWithFee(address(this), rewardPoolAddress, _currentBalance); return true; } //Transfer ownership to new owner function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "New owner cannot be a zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } //Remove owner from the contract function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner, address(0)); owner = address(0); } //Modifiers modifier onlyOwner() { require(owner == msg.sender, "Only current owner can call this function"); _; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
0x608060405234801561001057600080fd5b506004361061010b5760003560e01c80637547c7a3116100a2578063a5ce413b11610071578063a5ce413b14610314578063aa9a091214610334578063caaf94f51461038a578063f6b4dfb4146103a8578063fe8b1cce146103dc5761010b565b80637547c7a3146102605780637a5c08ae146102a45780638da5cb5b146102c2578063a34b0f76146102f65761010b565b80634bd9351b116100de5780634bd9351b1461018a57806355a373d6146101a85780636bf301a4146101dc5780637033c04e146101fa5761010b565b806304dd1be5146101105780630e15561a1461012e578063372500ab1461014c5780634a023dc91461016c575b600080fd5b61011861040a565b6040518082815260200191505060405180910390f35b610136610410565b6040518082815260200191505060405180910390f35b610154610416565b60405180821515815260200191505060405180910390f35b610174610837565b6040518082815260200191505060405180910390f35b61019261083d565b6040518082815260200191505060405180910390f35b6101b0610843565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6101e4610869565b6040518082815260200191505060405180910390f35b61023c6004803603602081101561021057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061086f565b60405180848152602001838152602001828152602001935050505060405180910390f35b61028c6004803603602081101561027657600080fd5b810190808035906020019092919050505061094a565b60405180821515815260200191505060405180910390f35b6102ac610e8f565b6040518082815260200191505060405180910390f35b6102ca610f6e565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102fe610f92565b6040518082815260200191505060405180910390f35b61031c610f98565b60405180821515815260200191505060405180910390f35b6103746004803603606081101561034a57600080fd5b81019080803590602001909291908035906020019092919080359060200190929190505050611305565b6040518082815260200191505060405180910390f35b6103926113e3565b6040518082815260200191505060405180910390f35b6103b06113e9565b604051808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610408600480360360208110156103f257600080fd5b810190808035906020019092919050505061140f565b005b60045481565b60025481565b6000610434600354610426610e8f565b6114bd90919063ffffffff16565b6002819055506000600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000154116104d5576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806118e66021913960400191505060405180910390fd5b600554600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060020154014211610573576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260418152602001806118a56041913960600191505060405180910390fd5b60006105cc600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206001015460025461154590919063ffffffff16565b90506000610621600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000154612710600454611305565b905060006106328383612710611305565b9050600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156106c757600080fd5b505af11580156106db573d6000803e3d6000fd5b505050506040513d60208110156106f157600080fd5b810190808051906020019092919050505061070b57600080fd5b600254600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206001018190555042600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600201819055506107b0816003546114bd90919063ffffffff16565b6003819055506107d26003546107c4610e8f565b6114bd90919063ffffffff16565b6002819055507f2a2d1456672a2b5013c6d74f8677f133bbf5f7d5bb6be09231f7814782b9a7173382604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a16001935050505090565b60085481565b60055481565b600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60065481565b6000806000600a60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000154600a60008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060010154600a60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600201549250925092509193909250565b600080600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001541415610b7e576006546007540282116109f4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806118626022913960400191505060405180910390fd5b600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd3330856040518463ffffffff1660e01b8152600401808473ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050602060405180830381600087803b158015610aa557600080fd5b505af1158015610ab9573d6000803e3d6000fd5b505050506040513d6020811015610acf57600080fd5b8101908080519060200190929190505050610ae957600080fd5b600254600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206001018190555042600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060020181905550610c74565b600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd3330856040518463ffffffff1660e01b8152600401808473ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050602060405180830381600087803b158015610c2f57600080fd5b505af1158015610c43573d6000803e3d6000fd5b505050506040513d6020811015610c5957600080fd5b8101908080519060200190929190505050610c7357600080fd5b5b6000610d3e6064610d30600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16637fd6f15c6040518163ffffffff1660e01b815260040160206040518083038186803b158015610ce657600080fd5b505afa158015610cfa573d6000803e3d6000fd5b505050506040513d6020811015610d1057600080fd5b81019080805190602001909291905050508661158f90919063ffffffff16565b61161590919063ffffffff16565b90506000610d55828561154590919063ffffffff16565b9050610dac81600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001546114bd90919063ffffffff16565b600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060000181905550610e07816004546114bd90919063ffffffff16565b600481905550610e29600354610e1b610e8f565b6114bd90919063ffffffff16565b6002819055507febedb8b3c678666e7f36970bc8f57abf6d8fa2e828c0da91ea5b75bf68ed101a3385604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a1600192505050919050565b6000610f69600454600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610f2057600080fd5b505afa158015610f34573d6000803e3d6000fd5b505050506040513d6020811015610f4a57600080fd5b810190808051906020019092919050505061154590919063ffffffff16565b905090565b60008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60035481565b600080600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001549050600061100a6064610ffc6008548561158f90919063ffffffff16565b61161590919063ffffffff16565b9050600061106382600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000015461154590919063ffffffff16565b9050600960009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663a9059cbb33836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156110f857600080fd5b505af115801561110c573d6000803e3d6000fd5b505050506040513d602081101561112257600080fd5b810190808051906020019092919050505061113c57600080fd5b6111518360045461154590919063ffffffff16565b6004819055506000600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600001819055506000600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600101819055506000600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206002018190555061124b60035461123d610e8f565b6114bd90919063ffffffff16565b6002819055507f85082129d87b2fe11527cb1b3b7a520aeb5aa6913f88a3d8757fe40d1db02fdd3382604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a17fc0642dc8ccff309ec5fee46fe88b07b8970d4980e2688bdeb2632906574a306a3383604051808373ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019250505060405180910390a16001935050505090565b6000806000611314868661165f565b9150915083811061132157fe5b6000848061132b57fe5b86880990508281111561133f576001820391505b80830392506000856000038616905080868161135757fe5b04955080848161136357fe5b049350600181826000038161137457fe5b04018302840193506000600190508087026002038102905080870260020381029050808702600203810290508087026002038102905080870260020381029050808702600203810290508087026002038102905080870260020381029050808502955050505050509392505050565b60075481565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b3373ffffffffffffffffffffffffffffffffffffffff1660008054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146114b3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260298152602001806118396029913960400191505060405180910390fd5b8060078190555050565b60008082840190508381101561153b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600061158783836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f7700008152506116b2565b905092915050565b6000808314156115a2576000905061160f565b60008284029050828482816115b357fe5b041461160a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806118846021913960400191505060405180910390fd5b809150505b92915050565b600061165783836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611772565b905092915050565b60008060007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8061168c57fe5b848609905083850292508281039150828110156116aa576001820391505b509250929050565b600083831115829061175f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611724578082015181840152602081019050611709565b50505050905090810190601f1680156117515780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b6000808311829061181e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156117e35780820151818401526020810190506117c8565b50505050905090810190601f1680156118105780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600083858161182a57fe5b04905080915050939250505056fe4f6e6c792063757272656e74206f776e65722063616e2063616c6c20746869732066756e6374696f6e4e6f7420656e6f75676820746f6b656e7320746f207374617274207374616b696e67536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77596f752063616e206f6e6c7920636c61696d20323420686f757273206166746572207374616b696e6720616e64206f6e636520657665727920323420686f757273596f7520646f206e6f74206861766520616e7920746f6b656e73207374616b6564a2646970667358221220cd843ab5910ad78be4c0f908609f80ef9dff1a90338dc3d652702171b05475ba64736f6c63430007020033
[ 4, 7 ]
0x569F1d106B3703EAfbA3fEb367f13387756d723D
pragma solidity 0.5.15; contract CairoVerifierContract { function verifyProofExternal( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata publicInput) external; } contract CpuConstraintPoly { // The Memory map during the execution of this contract is as follows: // [0x0, 0x20) - periodic_column/pedersen/points/x. // [0x20, 0x40) - periodic_column/pedersen/points/y. // [0x40, 0x60) - periodic_column/ecdsa/generator_points/x. // [0x60, 0x80) - periodic_column/ecdsa/generator_points/y. // [0x80, 0xa0) - trace_length. // [0xa0, 0xc0) - offset_size. // [0xc0, 0xe0) - half_offset_size. // [0xe0, 0x100) - initial_ap. // [0x100, 0x120) - initial_pc. // [0x120, 0x140) - final_ap. // [0x140, 0x160) - final_pc. // [0x160, 0x180) - memory/multi_column_perm/perm/interaction_elm. // [0x180, 0x1a0) - memory/multi_column_perm/hash_interaction_elm0. // [0x1a0, 0x1c0) - memory/multi_column_perm/perm/public_memory_prod. // [0x1c0, 0x1e0) - rc16/perm/interaction_elm. // [0x1e0, 0x200) - rc16/perm/public_memory_prod. // [0x200, 0x220) - rc_min. // [0x220, 0x240) - rc_max. // [0x240, 0x260) - pedersen/shift_point.x. // [0x260, 0x280) - pedersen/shift_point.y. // [0x280, 0x2a0) - initial_pedersen_addr. // [0x2a0, 0x2c0) - initial_rc_addr. // [0x2c0, 0x2e0) - ecdsa/sig_config.alpha. // [0x2e0, 0x300) - ecdsa/sig_config.shift_point.x. // [0x300, 0x320) - ecdsa/sig_config.shift_point.y. // [0x320, 0x340) - ecdsa/sig_config.beta. // [0x340, 0x360) - initial_ecdsa_addr. // [0x360, 0x380) - initial_checkpoints_addr. // [0x380, 0x3a0) - final_checkpoints_addr. // [0x3a0, 0x3c0) - trace_generator. // [0x3c0, 0x3e0) - oods_point. // [0x3e0, 0x440) - interaction_elements. // [0x440, 0x2980) - coefficients. // [0x2980, 0x3f40) - oods_values. // ----------------------- end of input data - ------------------------- // [0x3f40, 0x3f60) - composition_degree_bound. // [0x3f60, 0x3f80) - intermediate_value/cpu/decode/opcode_rc/bit_0. // [0x3f80, 0x3fa0) - intermediate_value/cpu/decode/opcode_rc/bit_1. // [0x3fa0, 0x3fc0) - intermediate_value/cpu/decode/opcode_rc/bit_2. // [0x3fc0, 0x3fe0) - intermediate_value/cpu/decode/opcode_rc/bit_4. // [0x3fe0, 0x4000) - intermediate_value/cpu/decode/opcode_rc/bit_3. // [0x4000, 0x4020) - intermediate_value/cpu/decode/opcode_rc/bit_9. // [0x4020, 0x4040) - intermediate_value/cpu/decode/opcode_rc/bit_5. // [0x4040, 0x4060) - intermediate_value/cpu/decode/opcode_rc/bit_6. // [0x4060, 0x4080) - intermediate_value/cpu/decode/opcode_rc/bit_7. // [0x4080, 0x40a0) - intermediate_value/cpu/decode/opcode_rc/bit_8. // [0x40a0, 0x40c0) - intermediate_value/npc_reg_0. // [0x40c0, 0x40e0) - intermediate_value/cpu/decode/opcode_rc/bit_10. // [0x40e0, 0x4100) - intermediate_value/cpu/decode/opcode_rc/bit_11. // [0x4100, 0x4120) - intermediate_value/cpu/decode/opcode_rc/bit_12. // [0x4120, 0x4140) - intermediate_value/cpu/decode/opcode_rc/bit_13. // [0x4140, 0x4160) - intermediate_value/cpu/decode/opcode_rc/bit_14. // [0x4160, 0x4180) - intermediate_value/memory/address_diff_0. // [0x4180, 0x41a0) - intermediate_value/rc16/diff_0. // [0x41a0, 0x41c0) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_0. // [0x41c0, 0x41e0) - intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0. // [0x41e0, 0x4200) - intermediate_value/pedersen/hash1/ec_subset_sum/bit_0. // [0x4200, 0x4220) - intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0. // [0x4220, 0x4240) - intermediate_value/pedersen/hash2/ec_subset_sum/bit_0. // [0x4240, 0x4260) - intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0. // [0x4260, 0x4280) - intermediate_value/pedersen/hash3/ec_subset_sum/bit_0. // [0x4280, 0x42a0) - intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0. // [0x42a0, 0x42c0) - intermediate_value/rc_builtin/value0_0. // [0x42c0, 0x42e0) - intermediate_value/rc_builtin/value1_0. // [0x42e0, 0x4300) - intermediate_value/rc_builtin/value2_0. // [0x4300, 0x4320) - intermediate_value/rc_builtin/value3_0. // [0x4320, 0x4340) - intermediate_value/rc_builtin/value4_0. // [0x4340, 0x4360) - intermediate_value/rc_builtin/value5_0. // [0x4360, 0x4380) - intermediate_value/rc_builtin/value6_0. // [0x4380, 0x43a0) - intermediate_value/rc_builtin/value7_0. // [0x43a0, 0x43c0) - intermediate_value/ecdsa/signature0/doubling_key/x_squared. // [0x43c0, 0x43e0) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0. // [0x43e0, 0x4400) - intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0. // [0x4400, 0x4420) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_0. // [0x4420, 0x4440) - intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0. // [0x4440, 0x46e0) - expmods. // [0x46e0, 0x49a0) - denominator_invs. // [0x49a0, 0x4c60) - denominators. // [0x4c60, 0x4dc0) - numerators. // [0x4dc0, 0x50a0) - adjustments. // [0x50a0, 0x5160) - expmod_context. function() external { uint256 res; assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 // Copy input from calldata to memory. calldatacopy(0x0, 0x0, /*Input data size*/ 0x3f40) let point := /*oods_point*/ mload(0x3c0) // Initialize composition_degree_bound to 2 * trace_length. mstore(0x3f40, mul(2, /*trace_length*/ mload(0x80))) function expmod(base, exponent, modulus) -> res { let p := /*expmod_context*/ 0x50a0 mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(not(0), 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } function degreeAdjustment(compositionPolynomialDegreeBound, constraintDegree, numeratorDegree, denominatorDegree) -> res { res := sub(sub(compositionPolynomialDegreeBound, 1), sub(add(constraintDegree, numeratorDegree), denominatorDegree)) } { // Prepare expmods for denominators and numerators. // expmods[0] = point^trace_length. mstore(0x4440, expmod(point, /*trace_length*/ mload(0x80), PRIME)) // expmods[1] = point^(trace_length / 16). mstore(0x4460, expmod(point, div(/*trace_length*/ mload(0x80), 16), PRIME)) // expmods[2] = point^(trace_length / 2). mstore(0x4480, expmod(point, div(/*trace_length*/ mload(0x80), 2), PRIME)) // expmods[3] = point^(trace_length / 8). mstore(0x44a0, expmod(point, div(/*trace_length*/ mload(0x80), 8), PRIME)) // expmods[4] = point^(trace_length / 256). mstore(0x44c0, expmod(point, div(/*trace_length*/ mload(0x80), 256), PRIME)) // expmods[5] = point^(trace_length / 512). mstore(0x44e0, expmod(point, div(/*trace_length*/ mload(0x80), 512), PRIME)) // expmods[6] = point^(trace_length / 128). mstore(0x4500, expmod(point, div(/*trace_length*/ mload(0x80), 128), PRIME)) // expmods[7] = point^(trace_length / 4096). mstore(0x4520, expmod(point, div(/*trace_length*/ mload(0x80), 4096), PRIME)) // expmods[8] = point^(trace_length / 32). mstore(0x4540, expmod(point, div(/*trace_length*/ mload(0x80), 32), PRIME)) // expmods[9] = point^(trace_length / 8192). mstore(0x4560, expmod(point, div(/*trace_length*/ mload(0x80), 8192), PRIME)) // expmods[10] = trace_generator^(15 * trace_length / 16). mstore(0x4580, expmod(/*trace_generator*/ mload(0x3a0), div(mul(15, /*trace_length*/ mload(0x80)), 16), PRIME)) // expmods[11] = trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x45a0, expmod(/*trace_generator*/ mload(0x3a0), mul(16, sub(div(/*trace_length*/ mload(0x80), 16), 1)), PRIME)) // expmods[12] = trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x45c0, expmod(/*trace_generator*/ mload(0x3a0), mul(2, sub(div(/*trace_length*/ mload(0x80), 2), 1)), PRIME)) // expmods[13] = trace_generator^(trace_length - 1). mstore(0x45e0, expmod(/*trace_generator*/ mload(0x3a0), sub(/*trace_length*/ mload(0x80), 1), PRIME)) // expmods[14] = trace_generator^(255 * trace_length / 256). mstore(0x4600, expmod(/*trace_generator*/ mload(0x3a0), div(mul(255, /*trace_length*/ mload(0x80)), 256), PRIME)) // expmods[15] = trace_generator^(63 * trace_length / 64). mstore(0x4620, expmod(/*trace_generator*/ mload(0x3a0), div(mul(63, /*trace_length*/ mload(0x80)), 64), PRIME)) // expmods[16] = trace_generator^(trace_length / 2). mstore(0x4640, expmod(/*trace_generator*/ mload(0x3a0), div(/*trace_length*/ mload(0x80), 2), PRIME)) // expmods[17] = trace_generator^(128 * (trace_length / 128 - 1)). mstore(0x4660, expmod(/*trace_generator*/ mload(0x3a0), mul(128, sub(div(/*trace_length*/ mload(0x80), 128), 1)), PRIME)) // expmods[18] = trace_generator^(251 * trace_length / 256). mstore(0x4680, expmod(/*trace_generator*/ mload(0x3a0), div(mul(251, /*trace_length*/ mload(0x80)), 256), PRIME)) // expmods[19] = trace_generator^(8192 * (trace_length / 8192 - 1)). mstore(0x46a0, expmod(/*trace_generator*/ mload(0x3a0), mul(8192, sub(div(/*trace_length*/ mload(0x80), 8192), 1)), PRIME)) // expmods[20] = trace_generator^(256 * (trace_length / 256 - 1)). mstore(0x46c0, expmod(/*trace_generator*/ mload(0x3a0), mul(256, sub(div(/*trace_length*/ mload(0x80), 256), 1)), PRIME)) } { // Prepare denominators for batch inverse. // Denominator for constraints: 'cpu/decode/opcode_rc/bit', 'rc16/perm/step0', 'rc16/diff_is_bit', 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // denominators[0] = point^trace_length - 1. mstore(0x49a0, addmod(/*point^trace_length*/ mload(0x4440), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'cpu/decode/opcode_rc/last_bit'. // denominators[1] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). mstore(0x49c0, addmod( /*point^(trace_length / 16)*/ mload(0x4460), sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x4580)), PRIME)) // Denominator for constraints: 'cpu/decode/opcode_rc_input', 'cpu/operands/mem_dst_addr', 'cpu/operands/mem0_addr', 'cpu/operands/mem1_addr', 'cpu/operands/ops_mul', 'cpu/operands/res', 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update', 'cpu/opcodes/call/push_fp', 'cpu/opcodes/call/push_pc', 'cpu/opcodes/assert_eq/assert_eq', 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // denominators[2] = point^(trace_length / 16) - 1. mstore(0x49e0, addmod(/*point^(trace_length / 16)*/ mload(0x4460), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'initial_ap', 'initial_fp', 'initial_pc', 'memory/multi_column_perm/perm/init0', 'rc16/perm/init0', 'rc16/minimum', 'pedersen/init_addr', 'rc_builtin/init_addr', 'ecdsa/init_addr', 'checkpoints/req_pc_init_addr'. // denominators[3] = point - 1. mstore(0x4a00, addmod(point, sub(PRIME, 1), PRIME)) // Denominator for constraints: 'final_ap', 'final_pc'. // denominators[4] = point - trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x4a20, addmod( point, sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x45a0)), PRIME)) // Denominator for constraints: 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // denominators[5] = point^(trace_length / 2) - 1. mstore(0x4a40, addmod(/*point^(trace_length / 2)*/ mload(0x4480), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'memory/multi_column_perm/perm/last'. // denominators[6] = point - trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x4a60, addmod( point, sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x45c0)), PRIME)) // Denominator for constraints: 'public_memory_addr_zero', 'public_memory_value_zero'. // denominators[7] = point^(trace_length / 8) - 1. mstore(0x4a80, addmod(/*point^(trace_length / 8)*/ mload(0x44a0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'rc16/perm/last', 'rc16/maximum'. // denominators[8] = point - trace_generator^(trace_length - 1). mstore(0x4aa0, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x45e0)), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/bit_extraction_end', 'pedersen/hash1/ec_subset_sum/bit_extraction_end', 'pedersen/hash2/ec_subset_sum/bit_extraction_end', 'pedersen/hash3/ec_subset_sum/bit_extraction_end'. // denominators[9] = point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). mstore(0x4ac0, addmod( /*point^(trace_length / 256)*/ mload(0x44c0), sub(PRIME, /*trace_generator^(63 * trace_length / 64)*/ mload(0x4620)), PRIME)) // Denominator for constraints: 'pedersen/hash0/ec_subset_sum/zeros_tail', 'pedersen/hash1/ec_subset_sum/zeros_tail', 'pedersen/hash2/ec_subset_sum/zeros_tail', 'pedersen/hash3/ec_subset_sum/zeros_tail'. // denominators[10] = point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). mstore(0x4ae0, addmod( /*point^(trace_length / 256)*/ mload(0x44c0), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x4600)), PRIME)) // Denominator for constraints: 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y', 'checkpoints/required_fp_addr', 'checkpoints/required_pc_next_addr', 'checkpoints/req_pc', 'checkpoints/req_fp'. // denominators[11] = point^(trace_length / 256) - 1. mstore(0x4b00, addmod(/*point^(trace_length / 256)*/ mload(0x44c0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'pedersen/hash0/init/x', 'pedersen/hash0/init/y', 'pedersen/hash1/init/x', 'pedersen/hash1/init/y', 'pedersen/hash2/init/x', 'pedersen/hash2/init/y', 'pedersen/hash3/init/x', 'pedersen/hash3/init/y', 'pedersen/input0_value0', 'pedersen/input0_value1', 'pedersen/input0_value2', 'pedersen/input0_value3', 'pedersen/input1_value0', 'pedersen/input1_value1', 'pedersen/input1_value2', 'pedersen/input1_value3', 'pedersen/output_value0', 'pedersen/output_value1', 'pedersen/output_value2', 'pedersen/output_value3'. // denominators[12] = point^(trace_length / 512) - 1. mstore(0x4b20, addmod(/*point^(trace_length / 512)*/ mload(0x44e0), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'pedersen/input0_addr', 'pedersen/input1_addr', 'pedersen/output_addr', 'rc_builtin/value', 'rc_builtin/addr_step'. // denominators[13] = point^(trace_length / 128) - 1. mstore(0x4b40, addmod(/*point^(trace_length / 128)*/ mload(0x4500), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // denominators[14] = point^(trace_length / 32) - 1. mstore(0x4b60, addmod(/*point^(trace_length / 32)*/ mload(0x4540), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/bit_extraction_end'. // denominators[15] = point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). mstore(0x4b80, addmod( /*point^(trace_length / 8192)*/ mload(0x4560), sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x4680)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_generator/zeros_tail'. // denominators[16] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). mstore(0x4ba0, addmod( /*point^(trace_length / 8192)*/ mload(0x4560), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x4600)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_key/bit_extraction_end'. // denominators[17] = point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). mstore(0x4bc0, addmod( /*point^(trace_length / 4096)*/ mload(0x4520), sub(PRIME, /*trace_generator^(251 * trace_length / 256)*/ mload(0x4680)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/exponentiate_key/zeros_tail'. // denominators[18] = point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). mstore(0x4be0, addmod( /*point^(trace_length / 4096)*/ mload(0x4520), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x4600)), PRIME)) // Denominator for constraints: 'ecdsa/signature0/init_gen/x', 'ecdsa/signature0/init_gen/y', 'ecdsa/signature0/add_results/slope', 'ecdsa/signature0/add_results/x', 'ecdsa/signature0/add_results/y', 'ecdsa/signature0/add_results/x_diff_inv', 'ecdsa/signature0/extract_r/slope', 'ecdsa/signature0/extract_r/x', 'ecdsa/signature0/extract_r/x_diff_inv', 'ecdsa/signature0/z_nonzero', 'ecdsa/signature0/q_on_curve/x_squared', 'ecdsa/signature0/q_on_curve/on_curve', 'ecdsa/message_addr', 'ecdsa/pubkey_addr', 'ecdsa/message_value0', 'ecdsa/pubkey_value0'. // denominators[19] = point^(trace_length / 8192) - 1. mstore(0x4c00, addmod(/*point^(trace_length / 8192)*/ mload(0x4560), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'ecdsa/signature0/init_key/x', 'ecdsa/signature0/init_key/y', 'ecdsa/signature0/r_and_w_nonzero'. // denominators[20] = point^(trace_length / 4096) - 1. mstore(0x4c20, addmod(/*point^(trace_length / 4096)*/ mload(0x4520), sub(PRIME, 1), PRIME)) // Denominator for constraints: 'checkpoints/req_pc_final_addr'. // denominators[21] = point - trace_generator^(256 * (trace_length / 256 - 1)). mstore(0x4c40, addmod( point, sub(PRIME, /*trace_generator^(256 * (trace_length / 256 - 1))*/ mload(0x46c0)), PRIME)) } { // Compute the inverses of the denominators into denominatorInvs using batch inverse. // Start by computing the cumulative product. // Let (d_0, d_1, d_2, ..., d_{n-1}) be the values in denominators. After this loop // denominatorInvs will be (1, d_0, d_0 * d_1, ...) and prod will contain the value of // d_0 * ... * d_{n-1}. // Compute the offset between the partialProducts array and the input values array. let productsToValuesOffset := 0x2c0 let prod := 1 let partialProductEndPtr := 0x49a0 for { let partialProductPtr := 0x46e0 } lt(partialProductPtr, partialProductEndPtr) { partialProductPtr := add(partialProductPtr, 0x20) } { mstore(partialProductPtr, prod) // prod *= d_{i}. prod := mulmod(prod, mload(add(partialProductPtr, productsToValuesOffset)), PRIME) } let firstPartialProductPtr := 0x46e0 // Compute the inverse of the product. let prodInv := expmod(prod, sub(PRIME, 2), PRIME) if eq(prodInv, 0) { // Solidity generates reverts with reason that look as follows: // 1. 4 bytes with the constant 0x08c379a0 (== Keccak256(b'Error(string)')[:4]). // 2. 32 bytes offset bytes (always 0x20 as far as i can tell). // 3. 32 bytes with the length of the revert reason. // 4. Revert reason string. mstore(0, 0x08c379a000000000000000000000000000000000000000000000000000000000) mstore(0x4, 0x20) mstore(0x24, 0x1e) mstore(0x44, "Batch inverse product is zero.") revert(0, 0x62) } // Compute the inverses. // Loop over denominator_invs in reverse order. // currentPartialProductPtr is initialized to one past the end. let currentPartialProductPtr := 0x49a0 for { } gt(currentPartialProductPtr, firstPartialProductPtr) { } { currentPartialProductPtr := sub(currentPartialProductPtr, 0x20) // Store 1/d_{i} = (d_0 * ... * d_{i-1}) * 1/(d_0 * ... * d_{i}). mstore(currentPartialProductPtr, mulmod(mload(currentPartialProductPtr), prodInv, PRIME)) // Update prodInv to be 1/(d_0 * ... * d_{i-1}) by multiplying by d_i. prodInv := mulmod(prodInv, mload(add(currentPartialProductPtr, productsToValuesOffset)), PRIME) } } { // Compute numerators and adjustment polynomials. // Numerator for constraints 'cpu/decode/opcode_rc/bit'. // numerators[0] = point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). mstore(0x4c60, addmod( /*point^(trace_length / 16)*/ mload(0x4460), sub(PRIME, /*trace_generator^(15 * trace_length / 16)*/ mload(0x4580)), PRIME)) // Numerator for constraints 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update'. // numerators[1] = point - trace_generator^(16 * (trace_length / 16 - 1)). mstore(0x4c80, addmod( point, sub(PRIME, /*trace_generator^(16 * (trace_length / 16 - 1))*/ mload(0x45a0)), PRIME)) // Numerator for constraints 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // numerators[2] = point - trace_generator^(2 * (trace_length / 2 - 1)). mstore(0x4ca0, addmod( point, sub(PRIME, /*trace_generator^(2 * (trace_length / 2 - 1))*/ mload(0x45c0)), PRIME)) // Numerator for constraints 'rc16/perm/step0', 'rc16/diff_is_bit'. // numerators[3] = point - trace_generator^(trace_length - 1). mstore(0x4cc0, addmod(point, sub(PRIME, /*trace_generator^(trace_length - 1)*/ mload(0x45e0)), PRIME)) // Numerator for constraints 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // numerators[4] = point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). mstore(0x4ce0, addmod( /*point^(trace_length / 256)*/ mload(0x44c0), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x4600)), PRIME)) // Numerator for constraints 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y'. // numerators[5] = point^(trace_length / 512) - trace_generator^(trace_length / 2). mstore(0x4d00, addmod( /*point^(trace_length / 512)*/ mload(0x44e0), sub(PRIME, /*trace_generator^(trace_length / 2)*/ mload(0x4640)), PRIME)) // Numerator for constraints 'pedersen/input0_addr', 'rc_builtin/addr_step'. // numerators[6] = point - trace_generator^(128 * (trace_length / 128 - 1)). mstore(0x4d20, addmod( point, sub(PRIME, /*trace_generator^(128 * (trace_length / 128 - 1))*/ mload(0x4660)), PRIME)) // Numerator for constraints 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // numerators[7] = point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). mstore(0x4d40, addmod( /*point^(trace_length / 4096)*/ mload(0x4520), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x4600)), PRIME)) // Numerator for constraints 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // numerators[8] = point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). mstore(0x4d60, addmod( /*point^(trace_length / 8192)*/ mload(0x4560), sub(PRIME, /*trace_generator^(255 * trace_length / 256)*/ mload(0x4600)), PRIME)) // Numerator for constraints 'ecdsa/pubkey_addr'. // numerators[9] = point - trace_generator^(8192 * (trace_length / 8192 - 1)). mstore(0x4d80, addmod( point, sub(PRIME, /*trace_generator^(8192 * (trace_length / 8192 - 1))*/ mload(0x46a0)), PRIME)) // Numerator for constraints 'checkpoints/required_pc_next_addr', 'checkpoints/req_pc', 'checkpoints/req_fp'. // numerators[10] = point - trace_generator^(256 * (trace_length / 256 - 1)). mstore(0x4da0, addmod( point, sub(PRIME, /*trace_generator^(256 * (trace_length / 256 - 1))*/ mload(0x46c0)), PRIME)) // Adjustment polynomial for constraints 'cpu/decode/opcode_rc/bit'. // adjustments[0] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 16, trace_length). mstore(0x4dc0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 16), /*trace_length*/ mload(0x80)), PRIME)) // Adjustment polynomial for constraints 'cpu/decode/opcode_rc/last_bit', 'cpu/operands/mem_dst_addr', 'cpu/operands/mem0_addr', 'cpu/operands/mem1_addr', 'cpu/operands/ops_mul', 'cpu/operands/res', 'cpu/opcodes/call/push_fp', 'cpu/opcodes/call/push_pc', 'cpu/opcodes/assert_eq/assert_eq'. // adjustments[1] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, trace_length / 16). mstore(0x4de0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'cpu/decode/opcode_rc_input'. // adjustments[2] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 16). mstore(0x4e00, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'cpu/update_registers/update_pc/tmp0', 'cpu/update_registers/update_pc/tmp1', 'cpu/update_registers/update_pc/pc_cond_negative', 'cpu/update_registers/update_pc/pc_cond_positive', 'cpu/update_registers/update_ap/ap_update', 'cpu/update_registers/update_fp/fp_update'. // adjustments[3] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length / 16). mstore(0x4e20, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'initial_ap', 'initial_fp', 'initial_pc', 'final_ap', 'final_pc', 'memory/multi_column_perm/perm/last', 'rc16/perm/last', 'rc16/minimum', 'rc16/maximum', 'pedersen/init_addr', 'rc_builtin/init_addr', 'ecdsa/init_addr', 'checkpoints/req_pc_init_addr', 'checkpoints/req_pc_final_addr'. // adjustments[4] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, 1). mstore(0x4e40, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, 1), PRIME)) // Adjustment polynomial for constraints 'memory/multi_column_perm/perm/init0', 'rc16/perm/init0'. // adjustments[5] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, 1). mstore(0x4e60, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, 1), PRIME)) // Adjustment polynomial for constraints 'memory/multi_column_perm/perm/step0', 'memory/diff_is_bit', 'memory/is_func'. // adjustments[6] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length / 2). mstore(0x4e80, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 2)), PRIME)) // Adjustment polynomial for constraints 'public_memory_addr_zero', 'public_memory_value_zero'. // adjustments[7] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 8). mstore(0x4ea0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 8)), PRIME)) // Adjustment polynomial for constraints 'rc16/perm/step0', 'rc16/diff_is_bit'. // adjustments[8] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length). mstore(0x4ec0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, /*trace_length*/ mload(0x80)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/ec_subset_sum/booleanity_test', 'pedersen/hash0/ec_subset_sum/add_points/slope', 'pedersen/hash0/ec_subset_sum/add_points/x', 'pedersen/hash0/ec_subset_sum/add_points/y', 'pedersen/hash0/ec_subset_sum/copy_point/x', 'pedersen/hash0/ec_subset_sum/copy_point/y', 'pedersen/hash1/ec_subset_sum/booleanity_test', 'pedersen/hash1/ec_subset_sum/add_points/slope', 'pedersen/hash1/ec_subset_sum/add_points/x', 'pedersen/hash1/ec_subset_sum/add_points/y', 'pedersen/hash1/ec_subset_sum/copy_point/x', 'pedersen/hash1/ec_subset_sum/copy_point/y', 'pedersen/hash2/ec_subset_sum/booleanity_test', 'pedersen/hash2/ec_subset_sum/add_points/slope', 'pedersen/hash2/ec_subset_sum/add_points/x', 'pedersen/hash2/ec_subset_sum/add_points/y', 'pedersen/hash2/ec_subset_sum/copy_point/x', 'pedersen/hash2/ec_subset_sum/copy_point/y', 'pedersen/hash3/ec_subset_sum/booleanity_test', 'pedersen/hash3/ec_subset_sum/add_points/slope', 'pedersen/hash3/ec_subset_sum/add_points/x', 'pedersen/hash3/ec_subset_sum/add_points/y', 'pedersen/hash3/ec_subset_sum/copy_point/x', 'pedersen/hash3/ec_subset_sum/copy_point/y'. // adjustments[9] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 256, trace_length). mstore(0x4ee0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 256), /*trace_length*/ mload(0x80)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/ec_subset_sum/bit_extraction_end', 'pedersen/hash0/ec_subset_sum/zeros_tail', 'pedersen/hash1/ec_subset_sum/bit_extraction_end', 'pedersen/hash1/ec_subset_sum/zeros_tail', 'pedersen/hash2/ec_subset_sum/bit_extraction_end', 'pedersen/hash2/ec_subset_sum/zeros_tail', 'pedersen/hash3/ec_subset_sum/bit_extraction_end', 'pedersen/hash3/ec_subset_sum/zeros_tail', 'checkpoints/required_fp_addr'. // adjustments[10] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 256). mstore(0x4f00, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 256)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/copy_point/x', 'pedersen/hash0/copy_point/y', 'pedersen/hash1/copy_point/x', 'pedersen/hash1/copy_point/y', 'pedersen/hash2/copy_point/x', 'pedersen/hash2/copy_point/y', 'pedersen/hash3/copy_point/x', 'pedersen/hash3/copy_point/y'. // adjustments[11] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, trace_length / 512, trace_length / 256). mstore(0x4f20, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), div(/*trace_length*/ mload(0x80), 512), div(/*trace_length*/ mload(0x80), 256)), PRIME)) // Adjustment polynomial for constraints 'pedersen/hash0/init/x', 'pedersen/hash0/init/y', 'pedersen/hash1/init/x', 'pedersen/hash1/init/y', 'pedersen/hash2/init/x', 'pedersen/hash2/init/y', 'pedersen/hash3/init/x', 'pedersen/hash3/init/y', 'pedersen/input0_value0', 'pedersen/input0_value1', 'pedersen/input0_value2', 'pedersen/input0_value3', 'pedersen/input1_value0', 'pedersen/input1_value1', 'pedersen/input1_value2', 'pedersen/input1_value3', 'pedersen/output_value0', 'pedersen/output_value1', 'pedersen/output_value2', 'pedersen/output_value3'. // adjustments[12] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 512). mstore(0x4f40, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 512)), PRIME)) // Adjustment polynomial for constraints 'pedersen/input0_addr', 'rc_builtin/addr_step'. // adjustments[13] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 1, trace_length / 128). mstore(0x4f60, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 1, div(/*trace_length*/ mload(0x80), 128)), PRIME)) // Adjustment polynomial for constraints 'pedersen/input1_addr', 'pedersen/output_addr', 'rc_builtin/value'. // adjustments[14] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 128). mstore(0x4f80, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 128)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/doubling_key/slope', 'ecdsa/signature0/doubling_key/x', 'ecdsa/signature0/doubling_key/y', 'ecdsa/signature0/exponentiate_key/booleanity_test', 'ecdsa/signature0/exponentiate_key/add_points/slope', 'ecdsa/signature0/exponentiate_key/add_points/x', 'ecdsa/signature0/exponentiate_key/add_points/y', 'ecdsa/signature0/exponentiate_key/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_key/copy_point/x', 'ecdsa/signature0/exponentiate_key/copy_point/y'. // adjustments[15] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 4096, trace_length / 16). mstore(0x4fa0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 4096), div(/*trace_length*/ mload(0x80), 16)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/exponentiate_generator/booleanity_test', 'ecdsa/signature0/exponentiate_generator/add_points/slope', 'ecdsa/signature0/exponentiate_generator/add_points/x', 'ecdsa/signature0/exponentiate_generator/add_points/y', 'ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv', 'ecdsa/signature0/exponentiate_generator/copy_point/x', 'ecdsa/signature0/exponentiate_generator/copy_point/y'. // adjustments[16] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), trace_length / 8192, trace_length / 32). mstore(0x4fc0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), div(/*trace_length*/ mload(0x80), 8192), div(/*trace_length*/ mload(0x80), 32)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/exponentiate_generator/bit_extraction_end', 'ecdsa/signature0/exponentiate_generator/zeros_tail', 'ecdsa/signature0/init_gen/x', 'ecdsa/signature0/init_gen/y', 'ecdsa/message_addr', 'ecdsa/message_value0', 'ecdsa/pubkey_value0'. // adjustments[17] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 8192). mstore(0x4fe0, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 8192)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/exponentiate_key/bit_extraction_end', 'ecdsa/signature0/exponentiate_key/zeros_tail', 'ecdsa/signature0/init_key/x', 'ecdsa/signature0/init_key/y'. // adjustments[18] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 0, trace_length / 4096). mstore(0x5000, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 0, div(/*trace_length*/ mload(0x80), 4096)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/add_results/slope', 'ecdsa/signature0/add_results/x', 'ecdsa/signature0/add_results/y', 'ecdsa/signature0/add_results/x_diff_inv', 'ecdsa/signature0/extract_r/slope', 'ecdsa/signature0/extract_r/x', 'ecdsa/signature0/extract_r/x_diff_inv', 'ecdsa/signature0/z_nonzero', 'ecdsa/signature0/q_on_curve/x_squared', 'ecdsa/signature0/q_on_curve/on_curve'. // adjustments[19] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, trace_length / 8192). mstore(0x5020, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, div(/*trace_length*/ mload(0x80), 8192)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/signature0/r_and_w_nonzero'. // adjustments[20] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 0, trace_length / 4096). mstore(0x5040, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 0, div(/*trace_length*/ mload(0x80), 4096)), PRIME)) // Adjustment polynomial for constraints 'ecdsa/pubkey_addr'. // adjustments[21] = point^degreeAdjustment(composition_degree_bound, trace_length - 1, 1, trace_length / 8192). mstore(0x5060, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), sub(/*trace_length*/ mload(0x80), 1), 1, div(/*trace_length*/ mload(0x80), 8192)), PRIME)) // Adjustment polynomial for constraints 'checkpoints/required_pc_next_addr', 'checkpoints/req_pc', 'checkpoints/req_fp'. // adjustments[22] = point^degreeAdjustment(composition_degree_bound, 2 * (trace_length - 1), 1, trace_length / 256). mstore(0x5080, expmod(point, degreeAdjustment(/*composition_degree_bound*/ mload(0x3f40), mul(2, sub(/*trace_length*/ mload(0x80), 1)), 1, div(/*trace_length*/ mload(0x80), 256)), PRIME)) } { // Compute the result of the composition polynomial. { // cpu/decode/opcode_rc/bit_0 = column1_row0 - (column1_row1 + column1_row1). let val := addmod( /*column1_row0*/ mload(0x2b00), sub( PRIME, addmod(/*column1_row1*/ mload(0x2b20), /*column1_row1*/ mload(0x2b20), PRIME)), PRIME) mstore(0x3f60, val) } { // cpu/decode/opcode_rc/bit_1 = column1_row1 - (column1_row2 + column1_row2). let val := addmod( /*column1_row1*/ mload(0x2b20), sub( PRIME, addmod(/*column1_row2*/ mload(0x2b40), /*column1_row2*/ mload(0x2b40), PRIME)), PRIME) mstore(0x3f80, val) } { // cpu/decode/opcode_rc/bit_2 = column1_row2 - (column1_row3 + column1_row3). let val := addmod( /*column1_row2*/ mload(0x2b40), sub( PRIME, addmod(/*column1_row3*/ mload(0x2b60), /*column1_row3*/ mload(0x2b60), PRIME)), PRIME) mstore(0x3fa0, val) } { // cpu/decode/opcode_rc/bit_4 = column1_row4 - (column1_row5 + column1_row5). let val := addmod( /*column1_row4*/ mload(0x2b80), sub( PRIME, addmod(/*column1_row5*/ mload(0x2ba0), /*column1_row5*/ mload(0x2ba0), PRIME)), PRIME) mstore(0x3fc0, val) } { // cpu/decode/opcode_rc/bit_3 = column1_row3 - (column1_row4 + column1_row4). let val := addmod( /*column1_row3*/ mload(0x2b60), sub( PRIME, addmod(/*column1_row4*/ mload(0x2b80), /*column1_row4*/ mload(0x2b80), PRIME)), PRIME) mstore(0x3fe0, val) } { // cpu/decode/opcode_rc/bit_9 = column1_row9 - (column1_row10 + column1_row10). let val := addmod( /*column1_row9*/ mload(0x2c20), sub( PRIME, addmod(/*column1_row10*/ mload(0x2c40), /*column1_row10*/ mload(0x2c40), PRIME)), PRIME) mstore(0x4000, val) } { // cpu/decode/opcode_rc/bit_5 = column1_row5 - (column1_row6 + column1_row6). let val := addmod( /*column1_row5*/ mload(0x2ba0), sub( PRIME, addmod(/*column1_row6*/ mload(0x2bc0), /*column1_row6*/ mload(0x2bc0), PRIME)), PRIME) mstore(0x4020, val) } { // cpu/decode/opcode_rc/bit_6 = column1_row6 - (column1_row7 + column1_row7). let val := addmod( /*column1_row6*/ mload(0x2bc0), sub( PRIME, addmod(/*column1_row7*/ mload(0x2be0), /*column1_row7*/ mload(0x2be0), PRIME)), PRIME) mstore(0x4040, val) } { // cpu/decode/opcode_rc/bit_7 = column1_row7 - (column1_row8 + column1_row8). let val := addmod( /*column1_row7*/ mload(0x2be0), sub( PRIME, addmod(/*column1_row8*/ mload(0x2c00), /*column1_row8*/ mload(0x2c00), PRIME)), PRIME) mstore(0x4060, val) } { // cpu/decode/opcode_rc/bit_8 = column1_row8 - (column1_row9 + column1_row9). let val := addmod( /*column1_row8*/ mload(0x2c00), sub( PRIME, addmod(/*column1_row9*/ mload(0x2c20), /*column1_row9*/ mload(0x2c20), PRIME)), PRIME) mstore(0x4080, val) } { // npc_reg_0 = column19_row0 + cpu__decode__opcode_rc__bit_2 + 1. let val := addmod( addmod( /*column19_row0*/ mload(0x33c0), /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x3fa0), PRIME), 1, PRIME) mstore(0x40a0, val) } { // cpu/decode/opcode_rc/bit_10 = column1_row10 - (column1_row11 + column1_row11). let val := addmod( /*column1_row10*/ mload(0x2c40), sub( PRIME, addmod(/*column1_row11*/ mload(0x2c60), /*column1_row11*/ mload(0x2c60), PRIME)), PRIME) mstore(0x40c0, val) } { // cpu/decode/opcode_rc/bit_11 = column1_row11 - (column1_row12 + column1_row12). let val := addmod( /*column1_row11*/ mload(0x2c60), sub( PRIME, addmod(/*column1_row12*/ mload(0x2c80), /*column1_row12*/ mload(0x2c80), PRIME)), PRIME) mstore(0x40e0, val) } { // cpu/decode/opcode_rc/bit_12 = column1_row12 - (column1_row13 + column1_row13). let val := addmod( /*column1_row12*/ mload(0x2c80), sub( PRIME, addmod(/*column1_row13*/ mload(0x2ca0), /*column1_row13*/ mload(0x2ca0), PRIME)), PRIME) mstore(0x4100, val) } { // cpu/decode/opcode_rc/bit_13 = column1_row13 - (column1_row14 + column1_row14). let val := addmod( /*column1_row13*/ mload(0x2ca0), sub( PRIME, addmod(/*column1_row14*/ mload(0x2cc0), /*column1_row14*/ mload(0x2cc0), PRIME)), PRIME) mstore(0x4120, val) } { // cpu/decode/opcode_rc/bit_14 = column1_row14 - (column1_row15 + column1_row15). let val := addmod( /*column1_row14*/ mload(0x2cc0), sub( PRIME, addmod(/*column1_row15*/ mload(0x2ce0), /*column1_row15*/ mload(0x2ce0), PRIME)), PRIME) mstore(0x4140, val) } { // memory/address_diff_0 = column20_row2 - column20_row0. let val := addmod(/*column20_row2*/ mload(0x3900), sub(PRIME, /*column20_row0*/ mload(0x38c0)), PRIME) mstore(0x4160, val) } { // rc16/diff_0 = column2_row1 - column2_row0. let val := addmod(/*column2_row1*/ mload(0x2d20), sub(PRIME, /*column2_row0*/ mload(0x2d00)), PRIME) mstore(0x4180, val) } { // pedersen/hash0/ec_subset_sum/bit_0 = column6_row0 - (column6_row1 + column6_row1). let val := addmod( /*column6_row0*/ mload(0x2e80), sub( PRIME, addmod(/*column6_row1*/ mload(0x2ea0), /*column6_row1*/ mload(0x2ea0), PRIME)), PRIME) mstore(0x41a0, val) } { // pedersen/hash0/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash0__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0)), PRIME) mstore(0x41c0, val) } { // pedersen/hash1/ec_subset_sum/bit_0 = column10_row0 - (column10_row1 + column10_row1). let val := addmod( /*column10_row0*/ mload(0x3020), sub( PRIME, addmod(/*column10_row1*/ mload(0x3040), /*column10_row1*/ mload(0x3040), PRIME)), PRIME) mstore(0x41e0, val) } { // pedersen/hash1/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash1__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41e0)), PRIME) mstore(0x4200, val) } { // pedersen/hash2/ec_subset_sum/bit_0 = column14_row0 - (column14_row1 + column14_row1). let val := addmod( /*column14_row0*/ mload(0x31c0), sub( PRIME, addmod(/*column14_row1*/ mload(0x31e0), /*column14_row1*/ mload(0x31e0), PRIME)), PRIME) mstore(0x4220, val) } { // pedersen/hash2/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash2__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4220)), PRIME) mstore(0x4240, val) } { // pedersen/hash3/ec_subset_sum/bit_0 = column18_row0 - (column18_row1 + column18_row1). let val := addmod( /*column18_row0*/ mload(0x3360), sub( PRIME, addmod(/*column18_row1*/ mload(0x3380), /*column18_row1*/ mload(0x3380), PRIME)), PRIME) mstore(0x4260, val) } { // pedersen/hash3/ec_subset_sum/bit_neg_0 = 1 - pedersen__hash3__ec_subset_sum__bit_0. let val := addmod( 1, sub(PRIME, /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4260)), PRIME) mstore(0x4280, val) } { // rc_builtin/value0_0 = column0_row12. let val := /*column0_row12*/ mload(0x2a00) mstore(0x42a0, val) } { // rc_builtin/value1_0 = rc_builtin__value0_0 * offset_size + column0_row28. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value0_0*/ mload(0x42a0), /*offset_size*/ mload(0xa0), PRIME), /*column0_row28*/ mload(0x2a20), PRIME) mstore(0x42c0, val) } { // rc_builtin/value2_0 = rc_builtin__value1_0 * offset_size + column0_row44. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value1_0*/ mload(0x42c0), /*offset_size*/ mload(0xa0), PRIME), /*column0_row44*/ mload(0x2a40), PRIME) mstore(0x42e0, val) } { // rc_builtin/value3_0 = rc_builtin__value2_0 * offset_size + column0_row60. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value2_0*/ mload(0x42e0), /*offset_size*/ mload(0xa0), PRIME), /*column0_row60*/ mload(0x2a60), PRIME) mstore(0x4300, val) } { // rc_builtin/value4_0 = rc_builtin__value3_0 * offset_size + column0_row76. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value3_0*/ mload(0x4300), /*offset_size*/ mload(0xa0), PRIME), /*column0_row76*/ mload(0x2a80), PRIME) mstore(0x4320, val) } { // rc_builtin/value5_0 = rc_builtin__value4_0 * offset_size + column0_row92. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value4_0*/ mload(0x4320), /*offset_size*/ mload(0xa0), PRIME), /*column0_row92*/ mload(0x2aa0), PRIME) mstore(0x4340, val) } { // rc_builtin/value6_0 = rc_builtin__value5_0 * offset_size + column0_row108. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value5_0*/ mload(0x4340), /*offset_size*/ mload(0xa0), PRIME), /*column0_row108*/ mload(0x2ac0), PRIME) mstore(0x4360, val) } { // rc_builtin/value7_0 = rc_builtin__value6_0 * offset_size + column0_row124. let val := addmod( mulmod( /*intermediate_value/rc_builtin/value6_0*/ mload(0x4360), /*offset_size*/ mload(0xa0), PRIME), /*column0_row124*/ mload(0x2ae0), PRIME) mstore(0x4380, val) } { // ecdsa/signature0/doubling_key/x_squared = column21_row6 * column21_row6. let val := mulmod(/*column21_row6*/ mload(0x3a00), /*column21_row6*/ mload(0x3a00), PRIME) mstore(0x43a0, val) } { // ecdsa/signature0/exponentiate_generator/bit_0 = column21_row31 - (column21_row63 + column21_row63). let val := addmod( /*column21_row31*/ mload(0x3c40), sub( PRIME, addmod(/*column21_row63*/ mload(0x3ca0), /*column21_row63*/ mload(0x3ca0), PRIME)), PRIME) mstore(0x43c0, val) } { // ecdsa/signature0/exponentiate_generator/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_generator__bit_0. let val := addmod( 1, sub( PRIME, /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x43c0)), PRIME) mstore(0x43e0, val) } { // ecdsa/signature0/exponentiate_key/bit_0 = column21_row3 - (column21_row19 + column21_row19). let val := addmod( /*column21_row3*/ mload(0x39a0), sub( PRIME, addmod(/*column21_row19*/ mload(0x3b60), /*column21_row19*/ mload(0x3b60), PRIME)), PRIME) mstore(0x4400, val) } { // ecdsa/signature0/exponentiate_key/bit_neg_0 = 1 - ecdsa__signature0__exponentiate_key__bit_0. let val := addmod( 1, sub( PRIME, /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4400)), PRIME) mstore(0x4420, val) } { // Constraint expression for cpu/decode/opcode_rc/bit: cpu__decode__opcode_rc__bit_0 * cpu__decode__opcode_rc__bit_0 - cpu__decode__opcode_rc__bit_0. let val := addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3f60), /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3f60), PRIME), sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3f60)), PRIME) // Numerator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). // val *= numerators[0]. val := mulmod(val, mload(0x4c60), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[0] + coefficients[1] * adjustments[0]). res := addmod(res, mulmod(val, add(/*coefficients[0]*/ mload(0x440), mulmod(/*coefficients[1]*/ mload(0x460), /*adjustments[0]*/mload(0x4dc0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/decode/opcode_rc/last_bit: column1_row0 * column1_row0 - column1_row0. let val := addmod( mulmod(/*column1_row0*/ mload(0x2b00), /*column1_row0*/ mload(0x2b00), PRIME), sub(PRIME, /*column1_row0*/ mload(0x2b00)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - trace_generator^(15 * trace_length / 16). // val *= denominator_invs[1]. val := mulmod(val, mload(0x4700), PRIME) // res += val * (coefficients[2] + coefficients[3] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[2]*/ mload(0x480), mulmod(/*coefficients[3]*/ mload(0x4a0), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/decode/opcode_rc_input: column19_row1 - (((column1_row0 * offset_size + column0_row4) * offset_size + column0_row8) * offset_size + column0_row0). let val := addmod( /*column19_row1*/ mload(0x33e0), sub( PRIME, addmod( mulmod( addmod( mulmod( addmod( mulmod(/*column1_row0*/ mload(0x2b00), /*offset_size*/ mload(0xa0), PRIME), /*column0_row4*/ mload(0x29c0), PRIME), /*offset_size*/ mload(0xa0), PRIME), /*column0_row8*/ mload(0x29e0), PRIME), /*offset_size*/ mload(0xa0), PRIME), /*column0_row0*/ mload(0x2980), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[4] + coefficients[5] * adjustments[2]). res := addmod(res, mulmod(val, add(/*coefficients[4]*/ mload(0x4c0), mulmod(/*coefficients[5]*/ mload(0x4e0), /*adjustments[2]*/mload(0x4e00), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem_dst_addr: column19_row8 + half_offset_size - (cpu__decode__opcode_rc__bit_0 * column21_row8 + (1 - cpu__decode__opcode_rc__bit_0) * column21_row0 + column0_row0). let val := addmod( addmod(/*column19_row8*/ mload(0x34c0), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3f60), /*column21_row8*/ mload(0x3a40), PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_0*/ mload(0x3f60)), PRIME), /*column21_row0*/ mload(0x3940), PRIME), PRIME), /*column0_row0*/ mload(0x2980), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[6] + coefficients[7] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[6]*/ mload(0x500), mulmod(/*coefficients[7]*/ mload(0x520), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem0_addr: column19_row4 + half_offset_size - (cpu__decode__opcode_rc__bit_1 * column21_row8 + (1 - cpu__decode__opcode_rc__bit_1) * column21_row0 + column0_row8). let val := addmod( addmod(/*column19_row4*/ mload(0x3440), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x3f80), /*column21_row8*/ mload(0x3a40), PRIME), mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_1*/ mload(0x3f80)), PRIME), /*column21_row0*/ mload(0x3940), PRIME), PRIME), /*column0_row8*/ mload(0x29e0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[8] + coefficients[9] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[8]*/ mload(0x540), mulmod(/*coefficients[9]*/ mload(0x560), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/mem1_addr: column19_row12 + half_offset_size - (cpu__decode__opcode_rc__bit_2 * column19_row0 + cpu__decode__opcode_rc__bit_4 * column21_row0 + cpu__decode__opcode_rc__bit_3 * column21_row8 + (1 - (cpu__decode__opcode_rc__bit_2 + cpu__decode__opcode_rc__bit_4 + cpu__decode__opcode_rc__bit_3)) * column19_row5 + column0_row4). let val := addmod( addmod(/*column19_row12*/ mload(0x3500), /*half_offset_size*/ mload(0xc0), PRIME), sub( PRIME, addmod( addmod( addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x3fa0), /*column19_row0*/ mload(0x33c0), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x3fc0), /*column21_row0*/ mload(0x3940), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x3fe0), /*column21_row8*/ mload(0x3a40), PRIME), PRIME), mulmod( addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x3fa0), /*intermediate_value/cpu/decode/opcode_rc/bit_4*/ mload(0x3fc0), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_3*/ mload(0x3fe0), PRIME)), PRIME), /*column19_row5*/ mload(0x3460), PRIME), PRIME), /*column0_row4*/ mload(0x29c0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[10] + coefficients[11] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[10]*/ mload(0x580), mulmod(/*coefficients[11]*/ mload(0x5a0), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/ops_mul: column21_row4 - column19_row5 * column19_row13. let val := addmod( /*column21_row4*/ mload(0x39c0), sub( PRIME, mulmod(/*column19_row5*/ mload(0x3460), /*column19_row13*/ mload(0x3520), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[12] + coefficients[13] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[12]*/ mload(0x5c0), mulmod(/*coefficients[13]*/ mload(0x5e0), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/operands/res: (1 - cpu__decode__opcode_rc__bit_9) * column21_row12 - (cpu__decode__opcode_rc__bit_5 * (column19_row5 + column19_row13) + cpu__decode__opcode_rc__bit_6 * column21_row4 + (1 - (cpu__decode__opcode_rc__bit_5 + cpu__decode__opcode_rc__bit_6 + cpu__decode__opcode_rc__bit_9)) * column19_row13). let val := addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4000)), PRIME), /*column21_row12*/ mload(0x3ac0), PRIME), sub( PRIME, addmod( addmod( mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x4020), addmod(/*column19_row5*/ mload(0x3460), /*column19_row13*/ mload(0x3520), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x4040), /*column21_row4*/ mload(0x39c0), PRIME), PRIME), mulmod( addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_5*/ mload(0x4020), /*intermediate_value/cpu/decode/opcode_rc/bit_6*/ mload(0x4040), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4000), PRIME)), PRIME), /*column19_row13*/ mload(0x3520), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[14] + coefficients[15] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[14]*/ mload(0x600), mulmod(/*coefficients[15]*/ mload(0x620), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/tmp0: column21_row2 - cpu__decode__opcode_rc__bit_9 * column19_row9. let val := addmod( /*column21_row2*/ mload(0x3980), sub( PRIME, mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4000), /*column19_row9*/ mload(0x34e0), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x4c80), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[16] + coefficients[17] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[16]*/ mload(0x640), mulmod(/*coefficients[17]*/ mload(0x660), /*adjustments[3]*/mload(0x4e20), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/tmp1: column21_row10 - column21_row2 * column21_row12. let val := addmod( /*column21_row10*/ mload(0x3a80), sub( PRIME, mulmod(/*column21_row2*/ mload(0x3980), /*column21_row12*/ mload(0x3ac0), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x4c80), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[18] + coefficients[19] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[18]*/ mload(0x680), mulmod(/*coefficients[19]*/ mload(0x6a0), /*adjustments[3]*/mload(0x4e20), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/pc_cond_negative: (1 - cpu__decode__opcode_rc__bit_9) * column19_row16 + column21_row2 * (column19_row16 - (column19_row0 + column19_row13)) - ((1 - (cpu__decode__opcode_rc__bit_7 + cpu__decode__opcode_rc__bit_8 + cpu__decode__opcode_rc__bit_9)) * npc_reg_0 + cpu__decode__opcode_rc__bit_7 * column21_row12 + cpu__decode__opcode_rc__bit_8 * (column19_row0 + column21_row12)). let val := addmod( addmod( mulmod( addmod( 1, sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4000)), PRIME), /*column19_row16*/ mload(0x3540), PRIME), mulmod( /*column21_row2*/ mload(0x3980), addmod( /*column19_row16*/ mload(0x3540), sub( PRIME, addmod(/*column19_row0*/ mload(0x33c0), /*column19_row13*/ mload(0x3520), PRIME)), PRIME), PRIME), PRIME), sub( PRIME, addmod( addmod( mulmod( addmod( 1, sub( PRIME, addmod( addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x4060), /*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x4080), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4000), PRIME)), PRIME), /*intermediate_value/npc_reg_0*/ mload(0x40a0), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_7*/ mload(0x4060), /*column21_row12*/ mload(0x3ac0), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_8*/ mload(0x4080), addmod(/*column19_row0*/ mload(0x33c0), /*column21_row12*/ mload(0x3ac0), PRIME), PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x4c80), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[20] + coefficients[21] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[20]*/ mload(0x6c0), mulmod(/*coefficients[21]*/ mload(0x6e0), /*adjustments[3]*/mload(0x4e20), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_pc/pc_cond_positive: (column21_row10 - cpu__decode__opcode_rc__bit_9) * (column19_row16 - npc_reg_0). let val := mulmod( addmod( /*column21_row10*/ mload(0x3a80), sub(PRIME, /*intermediate_value/cpu/decode/opcode_rc/bit_9*/ mload(0x4000)), PRIME), addmod( /*column19_row16*/ mload(0x3540), sub(PRIME, /*intermediate_value/npc_reg_0*/ mload(0x40a0)), PRIME), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x4c80), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[22] + coefficients[23] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[22]*/ mload(0x700), mulmod(/*coefficients[23]*/ mload(0x720), /*adjustments[3]*/mload(0x4e20), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_ap/ap_update: column21_row16 - (column21_row0 + cpu__decode__opcode_rc__bit_10 * column21_row12 + cpu__decode__opcode_rc__bit_11 + cpu__decode__opcode_rc__bit_12 * 2). let val := addmod( /*column21_row16*/ mload(0x3b40), sub( PRIME, addmod( addmod( addmod( /*column21_row0*/ mload(0x3940), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_10*/ mload(0x40c0), /*column21_row12*/ mload(0x3ac0), PRIME), PRIME), /*intermediate_value/cpu/decode/opcode_rc/bit_11*/ mload(0x40e0), PRIME), mulmod(/*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4100), 2, PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x4c80), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[24] + coefficients[25] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[24]*/ mload(0x740), mulmod(/*coefficients[25]*/ mload(0x760), /*adjustments[3]*/mload(0x4e20), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/update_registers/update_fp/fp_update: column21_row24 - ((1 - (cpu__decode__opcode_rc__bit_12 + cpu__decode__opcode_rc__bit_13)) * column21_row8 + cpu__decode__opcode_rc__bit_13 * column19_row9 + cpu__decode__opcode_rc__bit_12 * (column21_row0 + 2)). let val := addmod( /*column21_row24*/ mload(0x3be0), sub( PRIME, addmod( addmod( mulmod( addmod( 1, sub( PRIME, addmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4100), /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x4120), PRIME)), PRIME), /*column21_row8*/ mload(0x3a40), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_13*/ mload(0x4120), /*column19_row9*/ mload(0x34e0), PRIME), PRIME), mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4100), addmod(/*column21_row0*/ mload(0x3940), 2, PRIME), PRIME), PRIME)), PRIME) // Numerator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= numerators[1]. val := mulmod(val, mload(0x4c80), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[26] + coefficients[27] * adjustments[3]). res := addmod(res, mulmod(val, add(/*coefficients[26]*/ mload(0x780), mulmod(/*coefficients[27]*/ mload(0x7a0), /*adjustments[3]*/mload(0x4e20), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/push_fp: cpu__decode__opcode_rc__bit_12 * (column19_row9 - column21_row8). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4100), addmod(/*column19_row9*/ mload(0x34e0), sub(PRIME, /*column21_row8*/ mload(0x3a40)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[28] + coefficients[29] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[28]*/ mload(0x7c0), mulmod(/*coefficients[29]*/ mload(0x7e0), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/call/push_pc: cpu__decode__opcode_rc__bit_12 * (column19_row5 - (column19_row0 + cpu__decode__opcode_rc__bit_2 + 1)). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_12*/ mload(0x4100), addmod( /*column19_row5*/ mload(0x3460), sub( PRIME, addmod( addmod( /*column19_row0*/ mload(0x33c0), /*intermediate_value/cpu/decode/opcode_rc/bit_2*/ mload(0x3fa0), PRIME), 1, PRIME)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[30] + coefficients[31] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[30]*/ mload(0x800), mulmod(/*coefficients[31]*/ mload(0x820), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for cpu/opcodes/assert_eq/assert_eq: cpu__decode__opcode_rc__bit_14 * (column19_row9 - column21_row12). let val := mulmod( /*intermediate_value/cpu/decode/opcode_rc/bit_14*/ mload(0x4140), addmod( /*column19_row9*/ mload(0x34e0), sub(PRIME, /*column21_row12*/ mload(0x3ac0)), PRIME), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[32] + coefficients[33] * adjustments[1]). res := addmod(res, mulmod(val, add(/*coefficients[32]*/ mload(0x840), mulmod(/*coefficients[33]*/ mload(0x860), /*adjustments[1]*/mload(0x4de0), PRIME)), PRIME), PRIME) } { // Constraint expression for initial_ap: column21_row0 - initial_ap. let val := addmod(/*column21_row0*/ mload(0x3940), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[34] + coefficients[35] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[34]*/ mload(0x880), mulmod(/*coefficients[35]*/ mload(0x8a0), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for initial_fp: column21_row8 - initial_ap. let val := addmod(/*column21_row8*/ mload(0x3a40), sub(PRIME, /*initial_ap*/ mload(0xe0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[36] + coefficients[37] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[36]*/ mload(0x8c0), mulmod(/*coefficients[37]*/ mload(0x8e0), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for initial_pc: column19_row0 - initial_pc. let val := addmod(/*column19_row0*/ mload(0x33c0), sub(PRIME, /*initial_pc*/ mload(0x100)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[38] + coefficients[39] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[38]*/ mload(0x900), mulmod(/*coefficients[39]*/ mload(0x920), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for final_ap: column21_row0 - final_ap. let val := addmod(/*column21_row0*/ mload(0x3940), sub(PRIME, /*final_ap*/ mload(0x120)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= denominator_invs[4]. val := mulmod(val, mload(0x4760), PRIME) // res += val * (coefficients[40] + coefficients[41] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[40]*/ mload(0x940), mulmod(/*coefficients[41]*/ mload(0x960), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for final_pc: column19_row0 - final_pc. let val := addmod(/*column19_row0*/ mload(0x33c0), sub(PRIME, /*final_pc*/ mload(0x140)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(16 * (trace_length / 16 - 1)). // val *= denominator_invs[4]. val := mulmod(val, mload(0x4760), PRIME) // res += val * (coefficients[42] + coefficients[43] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[42]*/ mload(0x980), mulmod(/*coefficients[43]*/ mload(0x9a0), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/init0: (memory/multi_column_perm/perm/interaction_elm - (column20_row0 + memory/multi_column_perm/hash_interaction_elm0 * column20_row1)) * column24_inter1_row0 + column19_row0 + memory/multi_column_perm/hash_interaction_elm0 * column19_row1 - memory/multi_column_perm/perm/interaction_elm. let val := addmod( addmod( addmod( mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column20_row0*/ mload(0x38c0), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column20_row1*/ mload(0x38e0), PRIME), PRIME)), PRIME), /*column24_inter1_row0*/ mload(0x3f00), PRIME), /*column19_row0*/ mload(0x33c0), PRIME), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column19_row1*/ mload(0x33e0), PRIME), PRIME), sub(PRIME, /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[44] + coefficients[45] * adjustments[5]). res := addmod(res, mulmod(val, add(/*coefficients[44]*/ mload(0x9c0), mulmod(/*coefficients[45]*/ mload(0x9e0), /*adjustments[5]*/mload(0x4e60), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/step0: (memory/multi_column_perm/perm/interaction_elm - (column20_row2 + memory/multi_column_perm/hash_interaction_elm0 * column20_row3)) * column24_inter1_row2 - (memory/multi_column_perm/perm/interaction_elm - (column19_row2 + memory/multi_column_perm/hash_interaction_elm0 * column19_row3)) * column24_inter1_row0. let val := addmod( mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column20_row2*/ mload(0x3900), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column20_row3*/ mload(0x3920), PRIME), PRIME)), PRIME), /*column24_inter1_row2*/ mload(0x3f20), PRIME), sub( PRIME, mulmod( addmod( /*memory/multi_column_perm/perm/interaction_elm*/ mload(0x160), sub( PRIME, addmod( /*column19_row2*/ mload(0x3400), mulmod( /*memory/multi_column_perm/hash_interaction_elm0*/ mload(0x180), /*column19_row3*/ mload(0x3420), PRIME), PRIME)), PRIME), /*column24_inter1_row0*/ mload(0x3f00), PRIME)), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x4ca0), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x4780), PRIME) // res += val * (coefficients[46] + coefficients[47] * adjustments[6]). res := addmod(res, mulmod(val, add(/*coefficients[46]*/ mload(0xa00), mulmod(/*coefficients[47]*/ mload(0xa20), /*adjustments[6]*/mload(0x4e80), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/multi_column_perm/perm/last: column24_inter1_row0 - memory/multi_column_perm/perm/public_memory_prod. let val := addmod( /*column24_inter1_row0*/ mload(0x3f00), sub(PRIME, /*memory/multi_column_perm/perm/public_memory_prod*/ mload(0x1a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= denominator_invs[6]. val := mulmod(val, mload(0x47a0), PRIME) // res += val * (coefficients[48] + coefficients[49] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[48]*/ mload(0xa40), mulmod(/*coefficients[49]*/ mload(0xa60), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/diff_is_bit: memory__address_diff_0 * memory__address_diff_0 - memory__address_diff_0. let val := addmod( mulmod( /*intermediate_value/memory/address_diff_0*/ mload(0x4160), /*intermediate_value/memory/address_diff_0*/ mload(0x4160), PRIME), sub(PRIME, /*intermediate_value/memory/address_diff_0*/ mload(0x4160)), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x4ca0), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x4780), PRIME) // res += val * (coefficients[50] + coefficients[51] * adjustments[6]). res := addmod(res, mulmod(val, add(/*coefficients[50]*/ mload(0xa80), mulmod(/*coefficients[51]*/ mload(0xaa0), /*adjustments[6]*/mload(0x4e80), PRIME)), PRIME), PRIME) } { // Constraint expression for memory/is_func: (memory__address_diff_0 - 1) * (column20_row1 - column20_row3). let val := mulmod( addmod(/*intermediate_value/memory/address_diff_0*/ mload(0x4160), sub(PRIME, 1), PRIME), addmod(/*column20_row1*/ mload(0x38e0), sub(PRIME, /*column20_row3*/ mload(0x3920)), PRIME), PRIME) // Numerator: point - trace_generator^(2 * (trace_length / 2 - 1)). // val *= numerators[2]. val := mulmod(val, mload(0x4ca0), PRIME) // Denominator: point^(trace_length / 2) - 1. // val *= denominator_invs[5]. val := mulmod(val, mload(0x4780), PRIME) // res += val * (coefficients[52] + coefficients[53] * adjustments[6]). res := addmod(res, mulmod(val, add(/*coefficients[52]*/ mload(0xac0), mulmod(/*coefficients[53]*/ mload(0xae0), /*adjustments[6]*/mload(0x4e80), PRIME)), PRIME), PRIME) } { // Constraint expression for public_memory_addr_zero: column19_row2. let val := /*column19_row2*/ mload(0x3400) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8) - 1. // val *= denominator_invs[7]. val := mulmod(val, mload(0x47c0), PRIME) // res += val * (coefficients[54] + coefficients[55] * adjustments[7]). res := addmod(res, mulmod(val, add(/*coefficients[54]*/ mload(0xb00), mulmod(/*coefficients[55]*/ mload(0xb20), /*adjustments[7]*/mload(0x4ea0), PRIME)), PRIME), PRIME) } { // Constraint expression for public_memory_value_zero: column19_row3. let val := /*column19_row3*/ mload(0x3420) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8) - 1. // val *= denominator_invs[7]. val := mulmod(val, mload(0x47c0), PRIME) // res += val * (coefficients[56] + coefficients[57] * adjustments[7]). res := addmod(res, mulmod(val, add(/*coefficients[56]*/ mload(0xb40), mulmod(/*coefficients[57]*/ mload(0xb60), /*adjustments[7]*/mload(0x4ea0), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/perm/init0: (rc16/perm/interaction_elm - column2_row0) * column23_inter1_row0 + column0_row0 - rc16/perm/interaction_elm. let val := addmod( addmod( mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column2_row0*/ mload(0x2d00)), PRIME), /*column23_inter1_row0*/ mload(0x3ec0), PRIME), /*column0_row0*/ mload(0x2980), PRIME), sub(PRIME, /*rc16/perm/interaction_elm*/ mload(0x1c0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[58] + coefficients[59] * adjustments[5]). res := addmod(res, mulmod(val, add(/*coefficients[58]*/ mload(0xb80), mulmod(/*coefficients[59]*/ mload(0xba0), /*adjustments[5]*/mload(0x4e60), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/perm/step0: (rc16/perm/interaction_elm - column2_row1) * column23_inter1_row1 - (rc16/perm/interaction_elm - column0_row1) * column23_inter1_row0. let val := addmod( mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column2_row1*/ mload(0x2d20)), PRIME), /*column23_inter1_row1*/ mload(0x3ee0), PRIME), sub( PRIME, mulmod( addmod( /*rc16/perm/interaction_elm*/ mload(0x1c0), sub(PRIME, /*column0_row1*/ mload(0x29a0)), PRIME), /*column23_inter1_row0*/ mload(0x3ec0), PRIME)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[3]. val := mulmod(val, mload(0x4cc0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[60] + coefficients[61] * adjustments[8]). res := addmod(res, mulmod(val, add(/*coefficients[60]*/ mload(0xbc0), mulmod(/*coefficients[61]*/ mload(0xbe0), /*adjustments[8]*/mload(0x4ec0), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/perm/last: column23_inter1_row0 - rc16/perm/public_memory_prod. let val := addmod( /*column23_inter1_row0*/ mload(0x3ec0), sub(PRIME, /*rc16/perm/public_memory_prod*/ mload(0x1e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[8]. val := mulmod(val, mload(0x47e0), PRIME) // res += val * (coefficients[62] + coefficients[63] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[62]*/ mload(0xc00), mulmod(/*coefficients[63]*/ mload(0xc20), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/diff_is_bit: rc16__diff_0 * rc16__diff_0 - rc16__diff_0. let val := addmod( mulmod( /*intermediate_value/rc16/diff_0*/ mload(0x4180), /*intermediate_value/rc16/diff_0*/ mload(0x4180), PRIME), sub(PRIME, /*intermediate_value/rc16/diff_0*/ mload(0x4180)), PRIME) // Numerator: point - trace_generator^(trace_length - 1). // val *= numerators[3]. val := mulmod(val, mload(0x4cc0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[64] + coefficients[65] * adjustments[8]). res := addmod(res, mulmod(val, add(/*coefficients[64]*/ mload(0xc40), mulmod(/*coefficients[65]*/ mload(0xc60), /*adjustments[8]*/mload(0x4ec0), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/minimum: column2_row0 - rc_min. let val := addmod(/*column2_row0*/ mload(0x2d00), sub(PRIME, /*rc_min*/ mload(0x200)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[66] + coefficients[67] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[66]*/ mload(0xc80), mulmod(/*coefficients[67]*/ mload(0xca0), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for rc16/maximum: column2_row0 - rc_max. let val := addmod(/*column2_row0*/ mload(0x2d00), sub(PRIME, /*rc_max*/ mload(0x220)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(trace_length - 1). // val *= denominator_invs[8]. val := mulmod(val, mload(0x47e0), PRIME) // res += val * (coefficients[68] + coefficients[69] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[68]*/ mload(0xcc0), mulmod(/*coefficients[69]*/ mload(0xce0), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/booleanity_test: pedersen__hash0__ec_subset_sum__bit_0 * (pedersen__hash0__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0), addmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[70] + coefficients[71] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[70]*/ mload(0xd00), mulmod(/*coefficients[71]*/ mload(0xd20), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/bit_extraction_end: column6_row0. let val := /*column6_row0*/ mload(0x2e80) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[9]. val := mulmod(val, mload(0x4800), PRIME) // res += val * (coefficients[72] + coefficients[73] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[72]*/ mload(0xd40), mulmod(/*coefficients[73]*/ mload(0xd60), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/zeros_tail: column6_row0. let val := /*column6_row0*/ mload(0x2e80) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[10]. val := mulmod(val, mload(0x4820), PRIME) // res += val * (coefficients[74] + coefficients[75] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[74]*/ mload(0xd80), mulmod(/*coefficients[75]*/ mload(0xda0), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/slope: pedersen__hash0__ec_subset_sum__bit_0 * (column4_row0 - pedersen__points__y) - column5_row0 * (column3_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0), addmod( /*column4_row0*/ mload(0x2de0), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column5_row0*/ mload(0x2e60), addmod( /*column3_row0*/ mload(0x2d40), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[76] + coefficients[77] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[76]*/ mload(0xdc0), mulmod(/*coefficients[77]*/ mload(0xde0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/x: column5_row0 * column5_row0 - pedersen__hash0__ec_subset_sum__bit_0 * (column3_row0 + pedersen__points__x + column3_row1). let val := addmod( mulmod(/*column5_row0*/ mload(0x2e60), /*column5_row0*/ mload(0x2e60), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0), addmod( addmod( /*column3_row0*/ mload(0x2d40), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column3_row1*/ mload(0x2d60), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[78] + coefficients[79] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[78]*/ mload(0xe00), mulmod(/*coefficients[79]*/ mload(0xe20), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/add_points/y: pedersen__hash0__ec_subset_sum__bit_0 * (column4_row0 + column4_row1) - column5_row0 * (column3_row0 - column3_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_0*/ mload(0x41a0), addmod(/*column4_row0*/ mload(0x2de0), /*column4_row1*/ mload(0x2e00), PRIME), PRIME), sub( PRIME, mulmod( /*column5_row0*/ mload(0x2e60), addmod(/*column3_row0*/ mload(0x2d40), sub(PRIME, /*column3_row1*/ mload(0x2d60)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[80] + coefficients[81] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[80]*/ mload(0xe40), mulmod(/*coefficients[81]*/ mload(0xe60), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/x: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column3_row1 - column3_row0). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x41c0), addmod(/*column3_row1*/ mload(0x2d60), sub(PRIME, /*column3_row0*/ mload(0x2d40)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[82] + coefficients[83] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[82]*/ mload(0xe80), mulmod(/*coefficients[83]*/ mload(0xea0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/ec_subset_sum/copy_point/y: pedersen__hash0__ec_subset_sum__bit_neg_0 * (column4_row1 - column4_row0). let val := mulmod( /*intermediate_value/pedersen/hash0/ec_subset_sum/bit_neg_0*/ mload(0x41c0), addmod(/*column4_row1*/ mload(0x2e00), sub(PRIME, /*column4_row0*/ mload(0x2de0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[84] + coefficients[85] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[84]*/ mload(0xec0), mulmod(/*coefficients[85]*/ mload(0xee0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/copy_point/x: column3_row256 - column3_row255. let val := addmod( /*column3_row256*/ mload(0x2da0), sub(PRIME, /*column3_row255*/ mload(0x2d80)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[86] + coefficients[87] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[86]*/ mload(0xf00), mulmod(/*coefficients[87]*/ mload(0xf20), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/copy_point/y: column4_row256 - column4_row255. let val := addmod( /*column4_row256*/ mload(0x2e40), sub(PRIME, /*column4_row255*/ mload(0x2e20)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[88] + coefficients[89] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[88]*/ mload(0xf40), mulmod(/*coefficients[89]*/ mload(0xf60), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/init/x: column3_row0 - pedersen/shift_point.x. let val := addmod( /*column3_row0*/ mload(0x2d40), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[90] + coefficients[91] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[90]*/ mload(0xf80), mulmod(/*coefficients[91]*/ mload(0xfa0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash0/init/y: column4_row0 - pedersen/shift_point.y. let val := addmod( /*column4_row0*/ mload(0x2de0), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[92] + coefficients[93] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[92]*/ mload(0xfc0), mulmod(/*coefficients[93]*/ mload(0xfe0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/booleanity_test: pedersen__hash1__ec_subset_sum__bit_0 * (pedersen__hash1__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41e0), addmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41e0), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[94] + coefficients[95] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[94]*/ mload(0x1000), mulmod(/*coefficients[95]*/ mload(0x1020), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/bit_extraction_end: column10_row0. let val := /*column10_row0*/ mload(0x3020) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[9]. val := mulmod(val, mload(0x4800), PRIME) // res += val * (coefficients[96] + coefficients[97] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[96]*/ mload(0x1040), mulmod(/*coefficients[97]*/ mload(0x1060), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/zeros_tail: column10_row0. let val := /*column10_row0*/ mload(0x3020) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[10]. val := mulmod(val, mload(0x4820), PRIME) // res += val * (coefficients[98] + coefficients[99] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[98]*/ mload(0x1080), mulmod(/*coefficients[99]*/ mload(0x10a0), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/slope: pedersen__hash1__ec_subset_sum__bit_0 * (column8_row0 - pedersen__points__y) - column9_row0 * (column7_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41e0), addmod( /*column8_row0*/ mload(0x2f80), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column9_row0*/ mload(0x3000), addmod( /*column7_row0*/ mload(0x2ee0), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[100] + coefficients[101] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[100]*/ mload(0x10c0), mulmod(/*coefficients[101]*/ mload(0x10e0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/x: column9_row0 * column9_row0 - pedersen__hash1__ec_subset_sum__bit_0 * (column7_row0 + pedersen__points__x + column7_row1). let val := addmod( mulmod(/*column9_row0*/ mload(0x3000), /*column9_row0*/ mload(0x3000), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41e0), addmod( addmod( /*column7_row0*/ mload(0x2ee0), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column7_row1*/ mload(0x2f00), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[102] + coefficients[103] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[102]*/ mload(0x1100), mulmod(/*coefficients[103]*/ mload(0x1120), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/add_points/y: pedersen__hash1__ec_subset_sum__bit_0 * (column8_row0 + column8_row1) - column9_row0 * (column7_row0 - column7_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_0*/ mload(0x41e0), addmod(/*column8_row0*/ mload(0x2f80), /*column8_row1*/ mload(0x2fa0), PRIME), PRIME), sub( PRIME, mulmod( /*column9_row0*/ mload(0x3000), addmod(/*column7_row0*/ mload(0x2ee0), sub(PRIME, /*column7_row1*/ mload(0x2f00)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[104] + coefficients[105] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[104]*/ mload(0x1140), mulmod(/*coefficients[105]*/ mload(0x1160), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/x: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column7_row1 - column7_row0). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0*/ mload(0x4200), addmod(/*column7_row1*/ mload(0x2f00), sub(PRIME, /*column7_row0*/ mload(0x2ee0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[106] + coefficients[107] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[106]*/ mload(0x1180), mulmod(/*coefficients[107]*/ mload(0x11a0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/ec_subset_sum/copy_point/y: pedersen__hash1__ec_subset_sum__bit_neg_0 * (column8_row1 - column8_row0). let val := mulmod( /*intermediate_value/pedersen/hash1/ec_subset_sum/bit_neg_0*/ mload(0x4200), addmod(/*column8_row1*/ mload(0x2fa0), sub(PRIME, /*column8_row0*/ mload(0x2f80)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[108] + coefficients[109] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[108]*/ mload(0x11c0), mulmod(/*coefficients[109]*/ mload(0x11e0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/copy_point/x: column7_row256 - column7_row255. let val := addmod( /*column7_row256*/ mload(0x2f40), sub(PRIME, /*column7_row255*/ mload(0x2f20)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[110] + coefficients[111] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[110]*/ mload(0x1200), mulmod(/*coefficients[111]*/ mload(0x1220), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/copy_point/y: column8_row256 - column8_row255. let val := addmod( /*column8_row256*/ mload(0x2fe0), sub(PRIME, /*column8_row255*/ mload(0x2fc0)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[112] + coefficients[113] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[112]*/ mload(0x1240), mulmod(/*coefficients[113]*/ mload(0x1260), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/init/x: column7_row0 - pedersen/shift_point.x. let val := addmod( /*column7_row0*/ mload(0x2ee0), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[114] + coefficients[115] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[114]*/ mload(0x1280), mulmod(/*coefficients[115]*/ mload(0x12a0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash1/init/y: column8_row0 - pedersen/shift_point.y. let val := addmod( /*column8_row0*/ mload(0x2f80), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[116] + coefficients[117] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[116]*/ mload(0x12c0), mulmod(/*coefficients[117]*/ mload(0x12e0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/booleanity_test: pedersen__hash2__ec_subset_sum__bit_0 * (pedersen__hash2__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4220), addmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4220), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[118] + coefficients[119] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[118]*/ mload(0x1300), mulmod(/*coefficients[119]*/ mload(0x1320), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/bit_extraction_end: column14_row0. let val := /*column14_row0*/ mload(0x31c0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[9]. val := mulmod(val, mload(0x4800), PRIME) // res += val * (coefficients[120] + coefficients[121] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[120]*/ mload(0x1340), mulmod(/*coefficients[121]*/ mload(0x1360), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/zeros_tail: column14_row0. let val := /*column14_row0*/ mload(0x31c0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[10]. val := mulmod(val, mload(0x4820), PRIME) // res += val * (coefficients[122] + coefficients[123] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[122]*/ mload(0x1380), mulmod(/*coefficients[123]*/ mload(0x13a0), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/slope: pedersen__hash2__ec_subset_sum__bit_0 * (column12_row0 - pedersen__points__y) - column13_row0 * (column11_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4220), addmod( /*column12_row0*/ mload(0x3120), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column13_row0*/ mload(0x31a0), addmod( /*column11_row0*/ mload(0x3080), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[124] + coefficients[125] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[124]*/ mload(0x13c0), mulmod(/*coefficients[125]*/ mload(0x13e0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/x: column13_row0 * column13_row0 - pedersen__hash2__ec_subset_sum__bit_0 * (column11_row0 + pedersen__points__x + column11_row1). let val := addmod( mulmod(/*column13_row0*/ mload(0x31a0), /*column13_row0*/ mload(0x31a0), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4220), addmod( addmod( /*column11_row0*/ mload(0x3080), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column11_row1*/ mload(0x30a0), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[126] + coefficients[127] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[126]*/ mload(0x1400), mulmod(/*coefficients[127]*/ mload(0x1420), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/add_points/y: pedersen__hash2__ec_subset_sum__bit_0 * (column12_row0 + column12_row1) - column13_row0 * (column11_row0 - column11_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_0*/ mload(0x4220), addmod(/*column12_row0*/ mload(0x3120), /*column12_row1*/ mload(0x3140), PRIME), PRIME), sub( PRIME, mulmod( /*column13_row0*/ mload(0x31a0), addmod(/*column11_row0*/ mload(0x3080), sub(PRIME, /*column11_row1*/ mload(0x30a0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[128] + coefficients[129] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[128]*/ mload(0x1440), mulmod(/*coefficients[129]*/ mload(0x1460), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/x: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column11_row1 - column11_row0). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0*/ mload(0x4240), addmod(/*column11_row1*/ mload(0x30a0), sub(PRIME, /*column11_row0*/ mload(0x3080)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[130] + coefficients[131] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[130]*/ mload(0x1480), mulmod(/*coefficients[131]*/ mload(0x14a0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/ec_subset_sum/copy_point/y: pedersen__hash2__ec_subset_sum__bit_neg_0 * (column12_row1 - column12_row0). let val := mulmod( /*intermediate_value/pedersen/hash2/ec_subset_sum/bit_neg_0*/ mload(0x4240), addmod(/*column12_row1*/ mload(0x3140), sub(PRIME, /*column12_row0*/ mload(0x3120)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[132] + coefficients[133] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[132]*/ mload(0x14c0), mulmod(/*coefficients[133]*/ mload(0x14e0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/copy_point/x: column11_row256 - column11_row255. let val := addmod( /*column11_row256*/ mload(0x30e0), sub(PRIME, /*column11_row255*/ mload(0x30c0)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[134] + coefficients[135] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[134]*/ mload(0x1500), mulmod(/*coefficients[135]*/ mload(0x1520), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/copy_point/y: column12_row256 - column12_row255. let val := addmod( /*column12_row256*/ mload(0x3180), sub(PRIME, /*column12_row255*/ mload(0x3160)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[136] + coefficients[137] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[136]*/ mload(0x1540), mulmod(/*coefficients[137]*/ mload(0x1560), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/init/x: column11_row0 - pedersen/shift_point.x. let val := addmod( /*column11_row0*/ mload(0x3080), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[138] + coefficients[139] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[138]*/ mload(0x1580), mulmod(/*coefficients[139]*/ mload(0x15a0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash2/init/y: column12_row0 - pedersen/shift_point.y. let val := addmod( /*column12_row0*/ mload(0x3120), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[140] + coefficients[141] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[140]*/ mload(0x15c0), mulmod(/*coefficients[141]*/ mload(0x15e0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/booleanity_test: pedersen__hash3__ec_subset_sum__bit_0 * (pedersen__hash3__ec_subset_sum__bit_0 - 1). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4260), addmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4260), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[142] + coefficients[143] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[142]*/ mload(0x1600), mulmod(/*coefficients[143]*/ mload(0x1620), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/bit_extraction_end: column18_row0. let val := /*column18_row0*/ mload(0x3360) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(63 * trace_length / 64). // val *= denominator_invs[9]. val := mulmod(val, mload(0x4800), PRIME) // res += val * (coefficients[144] + coefficients[145] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[144]*/ mload(0x1640), mulmod(/*coefficients[145]*/ mload(0x1660), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/zeros_tail: column18_row0. let val := /*column18_row0*/ mload(0x3360) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[10]. val := mulmod(val, mload(0x4820), PRIME) // res += val * (coefficients[146] + coefficients[147] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[146]*/ mload(0x1680), mulmod(/*coefficients[147]*/ mload(0x16a0), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/slope: pedersen__hash3__ec_subset_sum__bit_0 * (column16_row0 - pedersen__points__y) - column17_row0 * (column15_row0 - pedersen__points__x). let val := addmod( mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4260), addmod( /*column16_row0*/ mload(0x32c0), sub(PRIME, /*periodic_column/pedersen/points/y*/ mload(0x20)), PRIME), PRIME), sub( PRIME, mulmod( /*column17_row0*/ mload(0x3340), addmod( /*column15_row0*/ mload(0x3220), sub(PRIME, /*periodic_column/pedersen/points/x*/ mload(0x0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[148] + coefficients[149] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[148]*/ mload(0x16c0), mulmod(/*coefficients[149]*/ mload(0x16e0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/x: column17_row0 * column17_row0 - pedersen__hash3__ec_subset_sum__bit_0 * (column15_row0 + pedersen__points__x + column15_row1). let val := addmod( mulmod(/*column17_row0*/ mload(0x3340), /*column17_row0*/ mload(0x3340), PRIME), sub( PRIME, mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4260), addmod( addmod( /*column15_row0*/ mload(0x3220), /*periodic_column/pedersen/points/x*/ mload(0x0), PRIME), /*column15_row1*/ mload(0x3240), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[150] + coefficients[151] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[150]*/ mload(0x1700), mulmod(/*coefficients[151]*/ mload(0x1720), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/add_points/y: pedersen__hash3__ec_subset_sum__bit_0 * (column16_row0 + column16_row1) - column17_row0 * (column15_row0 - column15_row1). let val := addmod( mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_0*/ mload(0x4260), addmod(/*column16_row0*/ mload(0x32c0), /*column16_row1*/ mload(0x32e0), PRIME), PRIME), sub( PRIME, mulmod( /*column17_row0*/ mload(0x3340), addmod(/*column15_row0*/ mload(0x3220), sub(PRIME, /*column15_row1*/ mload(0x3240)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[152] + coefficients[153] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[152]*/ mload(0x1740), mulmod(/*coefficients[153]*/ mload(0x1760), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/x: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column15_row1 - column15_row0). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0*/ mload(0x4280), addmod(/*column15_row1*/ mload(0x3240), sub(PRIME, /*column15_row0*/ mload(0x3220)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[154] + coefficients[155] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[154]*/ mload(0x1780), mulmod(/*coefficients[155]*/ mload(0x17a0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/ec_subset_sum/copy_point/y: pedersen__hash3__ec_subset_sum__bit_neg_0 * (column16_row1 - column16_row0). let val := mulmod( /*intermediate_value/pedersen/hash3/ec_subset_sum/bit_neg_0*/ mload(0x4280), addmod(/*column16_row1*/ mload(0x32e0), sub(PRIME, /*column16_row0*/ mload(0x32c0)), PRIME), PRIME) // Numerator: point^(trace_length / 256) - trace_generator^(255 * trace_length / 256). // val *= numerators[4]. val := mulmod(val, mload(0x4ce0), PRIME) // Denominator: point^trace_length - 1. // val *= denominator_invs[0]. val := mulmod(val, mload(0x46e0), PRIME) // res += val * (coefficients[156] + coefficients[157] * adjustments[9]). res := addmod(res, mulmod(val, add(/*coefficients[156]*/ mload(0x17c0), mulmod(/*coefficients[157]*/ mload(0x17e0), /*adjustments[9]*/mload(0x4ee0), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/copy_point/x: column15_row256 - column15_row255. let val := addmod( /*column15_row256*/ mload(0x3280), sub(PRIME, /*column15_row255*/ mload(0x3260)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[158] + coefficients[159] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[158]*/ mload(0x1800), mulmod(/*coefficients[159]*/ mload(0x1820), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/copy_point/y: column16_row256 - column16_row255. let val := addmod( /*column16_row256*/ mload(0x3320), sub(PRIME, /*column16_row255*/ mload(0x3300)), PRIME) // Numerator: point^(trace_length / 512) - trace_generator^(trace_length / 2). // val *= numerators[5]. val := mulmod(val, mload(0x4d00), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[160] + coefficients[161] * adjustments[11]). res := addmod(res, mulmod(val, add(/*coefficients[160]*/ mload(0x1840), mulmod(/*coefficients[161]*/ mload(0x1860), /*adjustments[11]*/mload(0x4f20), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/init/x: column15_row0 - pedersen/shift_point.x. let val := addmod( /*column15_row0*/ mload(0x3220), sub(PRIME, /*pedersen/shift_point.x*/ mload(0x240)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[162] + coefficients[163] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[162]*/ mload(0x1880), mulmod(/*coefficients[163]*/ mload(0x18a0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/hash3/init/y: column16_row0 - pedersen/shift_point.y. let val := addmod( /*column16_row0*/ mload(0x32c0), sub(PRIME, /*pedersen/shift_point.y*/ mload(0x260)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[164] + coefficients[165] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[164]*/ mload(0x18c0), mulmod(/*coefficients[165]*/ mload(0x18e0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value0: column19_row7 - column6_row0. let val := addmod(/*column19_row7*/ mload(0x34a0), sub(PRIME, /*column6_row0*/ mload(0x2e80)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[166] + coefficients[167] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[166]*/ mload(0x1900), mulmod(/*coefficients[167]*/ mload(0x1920), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value1: column19_row135 - column10_row0. let val := addmod( /*column19_row135*/ mload(0x36c0), sub(PRIME, /*column10_row0*/ mload(0x3020)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[168] + coefficients[169] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[168]*/ mload(0x1940), mulmod(/*coefficients[169]*/ mload(0x1960), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value2: column19_row263 - column14_row0. let val := addmod( /*column19_row263*/ mload(0x3780), sub(PRIME, /*column14_row0*/ mload(0x31c0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[170] + coefficients[171] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[170]*/ mload(0x1980), mulmod(/*coefficients[171]*/ mload(0x19a0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_value3: column19_row391 - column18_row0. let val := addmod( /*column19_row391*/ mload(0x37e0), sub(PRIME, /*column18_row0*/ mload(0x3360)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[172] + coefficients[173] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[172]*/ mload(0x19c0), mulmod(/*coefficients[173]*/ mload(0x19e0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input0_addr: column19_row134 - (column19_row38 + 1). let val := addmod( /*column19_row134*/ mload(0x36a0), sub(PRIME, addmod(/*column19_row38*/ mload(0x35a0), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). // val *= numerators[6]. val := mulmod(val, mload(0x4d20), PRIME) // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x4880), PRIME) // res += val * (coefficients[174] + coefficients[175] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[174]*/ mload(0x1a00), mulmod(/*coefficients[175]*/ mload(0x1a20), /*adjustments[13]*/mload(0x4f60), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/init_addr: column19_row6 - initial_pedersen_addr. let val := addmod( /*column19_row6*/ mload(0x3480), sub(PRIME, /*initial_pedersen_addr*/ mload(0x280)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[176] + coefficients[177] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[176]*/ mload(0x1a40), mulmod(/*coefficients[177]*/ mload(0x1a60), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value0: column19_row71 - column6_row256. let val := addmod( /*column19_row71*/ mload(0x3600), sub(PRIME, /*column6_row256*/ mload(0x2ec0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[178] + coefficients[179] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[178]*/ mload(0x1a80), mulmod(/*coefficients[179]*/ mload(0x1aa0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value1: column19_row199 - column10_row256. let val := addmod( /*column19_row199*/ mload(0x3740), sub(PRIME, /*column10_row256*/ mload(0x3060)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[180] + coefficients[181] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[180]*/ mload(0x1ac0), mulmod(/*coefficients[181]*/ mload(0x1ae0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value2: column19_row327 - column14_row256. let val := addmod( /*column19_row327*/ mload(0x37c0), sub(PRIME, /*column14_row256*/ mload(0x3200)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[182] + coefficients[183] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[182]*/ mload(0x1b00), mulmod(/*coefficients[183]*/ mload(0x1b20), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_value3: column19_row455 - column18_row256. let val := addmod( /*column19_row455*/ mload(0x3840), sub(PRIME, /*column18_row256*/ mload(0x33a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[184] + coefficients[185] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[184]*/ mload(0x1b40), mulmod(/*coefficients[185]*/ mload(0x1b60), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/input1_addr: column19_row70 - (column19_row6 + 1). let val := addmod( /*column19_row70*/ mload(0x35e0), sub(PRIME, addmod(/*column19_row6*/ mload(0x3480), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x4880), PRIME) // res += val * (coefficients[186] + coefficients[187] * adjustments[14]). res := addmod(res, mulmod(val, add(/*coefficients[186]*/ mload(0x1b80), mulmod(/*coefficients[187]*/ mload(0x1ba0), /*adjustments[14]*/mload(0x4f80), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value0: column19_row39 - column3_row511. let val := addmod( /*column19_row39*/ mload(0x35c0), sub(PRIME, /*column3_row511*/ mload(0x2dc0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[188] + coefficients[189] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[188]*/ mload(0x1bc0), mulmod(/*coefficients[189]*/ mload(0x1be0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value1: column19_row167 - column7_row511. let val := addmod( /*column19_row167*/ mload(0x3720), sub(PRIME, /*column7_row511*/ mload(0x2f60)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[190] + coefficients[191] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[190]*/ mload(0x1c00), mulmod(/*coefficients[191]*/ mload(0x1c20), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value2: column19_row295 - column11_row511. let val := addmod( /*column19_row295*/ mload(0x37a0), sub(PRIME, /*column11_row511*/ mload(0x3100)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[192] + coefficients[193] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[192]*/ mload(0x1c40), mulmod(/*coefficients[193]*/ mload(0x1c60), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_value3: column19_row423 - column15_row511. let val := addmod( /*column19_row423*/ mload(0x3820), sub(PRIME, /*column15_row511*/ mload(0x32a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 512) - 1. // val *= denominator_invs[12]. val := mulmod(val, mload(0x4860), PRIME) // res += val * (coefficients[194] + coefficients[195] * adjustments[12]). res := addmod(res, mulmod(val, add(/*coefficients[194]*/ mload(0x1c80), mulmod(/*coefficients[195]*/ mload(0x1ca0), /*adjustments[12]*/mload(0x4f40), PRIME)), PRIME), PRIME) } { // Constraint expression for pedersen/output_addr: column19_row38 - (column19_row70 + 1). let val := addmod( /*column19_row38*/ mload(0x35a0), sub(PRIME, addmod(/*column19_row70*/ mload(0x35e0), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x4880), PRIME) // res += val * (coefficients[196] + coefficients[197] * adjustments[14]). res := addmod(res, mulmod(val, add(/*coefficients[196]*/ mload(0x1cc0), mulmod(/*coefficients[197]*/ mload(0x1ce0), /*adjustments[14]*/mload(0x4f80), PRIME)), PRIME), PRIME) } { // Constraint expression for rc_builtin/value: rc_builtin__value7_0 - column19_row103. let val := addmod( /*intermediate_value/rc_builtin/value7_0*/ mload(0x4380), sub(PRIME, /*column19_row103*/ mload(0x3680)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x4880), PRIME) // res += val * (coefficients[198] + coefficients[199] * adjustments[14]). res := addmod(res, mulmod(val, add(/*coefficients[198]*/ mload(0x1d00), mulmod(/*coefficients[199]*/ mload(0x1d20), /*adjustments[14]*/mload(0x4f80), PRIME)), PRIME), PRIME) } { // Constraint expression for rc_builtin/addr_step: column19_row230 - (column19_row102 + 1). let val := addmod( /*column19_row230*/ mload(0x3760), sub(PRIME, addmod(/*column19_row102*/ mload(0x3660), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(128 * (trace_length / 128 - 1)). // val *= numerators[6]. val := mulmod(val, mload(0x4d20), PRIME) // Denominator: point^(trace_length / 128) - 1. // val *= denominator_invs[13]. val := mulmod(val, mload(0x4880), PRIME) // res += val * (coefficients[200] + coefficients[201] * adjustments[13]). res := addmod(res, mulmod(val, add(/*coefficients[200]*/ mload(0x1d40), mulmod(/*coefficients[201]*/ mload(0x1d60), /*adjustments[13]*/mload(0x4f60), PRIME)), PRIME), PRIME) } { // Constraint expression for rc_builtin/init_addr: column19_row102 - initial_rc_addr. let val := addmod( /*column19_row102*/ mload(0x3660), sub(PRIME, /*initial_rc_addr*/ mload(0x2a0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[202] + coefficients[203] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[202]*/ mload(0x1d80), mulmod(/*coefficients[203]*/ mload(0x1da0), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/slope: ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa__signature0__doubling_key__x_squared + ecdsa/sig_config.alpha - (column21_row14 + column21_row14) * column21_row1. let val := addmod( addmod( addmod( addmod( /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x43a0), /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x43a0), PRIME), /*intermediate_value/ecdsa/signature0/doubling_key/x_squared*/ mload(0x43a0), PRIME), /*ecdsa/sig_config.alpha*/ mload(0x2c0), PRIME), sub( PRIME, mulmod( addmod(/*column21_row14*/ mload(0x3b00), /*column21_row14*/ mload(0x3b00), PRIME), /*column21_row1*/ mload(0x3960), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[204] + coefficients[205] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[204]*/ mload(0x1dc0), mulmod(/*coefficients[205]*/ mload(0x1de0), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/x: column21_row1 * column21_row1 - (column21_row6 + column21_row6 + column21_row22). let val := addmod( mulmod(/*column21_row1*/ mload(0x3960), /*column21_row1*/ mload(0x3960), PRIME), sub( PRIME, addmod( addmod(/*column21_row6*/ mload(0x3a00), /*column21_row6*/ mload(0x3a00), PRIME), /*column21_row22*/ mload(0x3ba0), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[206] + coefficients[207] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[206]*/ mload(0x1e00), mulmod(/*coefficients[207]*/ mload(0x1e20), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/doubling_key/y: column21_row14 + column21_row30 - column21_row1 * (column21_row6 - column21_row22). let val := addmod( addmod(/*column21_row14*/ mload(0x3b00), /*column21_row30*/ mload(0x3c20), PRIME), sub( PRIME, mulmod( /*column21_row1*/ mload(0x3960), addmod( /*column21_row6*/ mload(0x3a00), sub(PRIME, /*column21_row22*/ mload(0x3ba0)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[208] + coefficients[209] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[208]*/ mload(0x1e40), mulmod(/*coefficients[209]*/ mload(0x1e60), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/booleanity_test: ecdsa__signature0__exponentiate_generator__bit_0 * (ecdsa__signature0__exponentiate_generator__bit_0 - 1). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x43c0), addmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x43c0), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x4d60), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x48a0), PRIME) // res += val * (coefficients[210] + coefficients[211] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[210]*/ mload(0x1e80), mulmod(/*coefficients[211]*/ mload(0x1ea0), /*adjustments[16]*/mload(0x4fc0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/bit_extraction_end: column21_row31. let val := /*column21_row31*/ mload(0x3c40) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - trace_generator^(251 * trace_length / 256). // val *= denominator_invs[15]. val := mulmod(val, mload(0x48c0), PRIME) // res += val * (coefficients[212] + coefficients[213] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[212]*/ mload(0x1ec0), mulmod(/*coefficients[213]*/ mload(0x1ee0), /*adjustments[17]*/mload(0x4fe0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/zeros_tail: column21_row31. let val := /*column21_row31*/ mload(0x3c40) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[16]. val := mulmod(val, mload(0x48e0), PRIME) // res += val * (coefficients[214] + coefficients[215] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[214]*/ mload(0x1f00), mulmod(/*coefficients[215]*/ mload(0x1f20), /*adjustments[17]*/mload(0x4fe0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/slope: ecdsa__signature0__exponentiate_generator__bit_0 * (column21_row23 - ecdsa__generator_points__y) - column21_row15 * (column21_row7 - ecdsa__generator_points__x). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x43c0), addmod( /*column21_row23*/ mload(0x3bc0), sub(PRIME, /*periodic_column/ecdsa/generator_points/y*/ mload(0x60)), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row15*/ mload(0x3b20), addmod( /*column21_row7*/ mload(0x3a20), sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x4d60), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x48a0), PRIME) // res += val * (coefficients[216] + coefficients[217] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[216]*/ mload(0x1f40), mulmod(/*coefficients[217]*/ mload(0x1f60), /*adjustments[16]*/mload(0x4fc0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x: column21_row15 * column21_row15 - ecdsa__signature0__exponentiate_generator__bit_0 * (column21_row7 + ecdsa__generator_points__x + column21_row39). let val := addmod( mulmod(/*column21_row15*/ mload(0x3b20), /*column21_row15*/ mload(0x3b20), PRIME), sub( PRIME, mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x43c0), addmod( addmod( /*column21_row7*/ mload(0x3a20), /*periodic_column/ecdsa/generator_points/x*/ mload(0x40), PRIME), /*column21_row39*/ mload(0x3c60), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x4d60), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x48a0), PRIME) // res += val * (coefficients[218] + coefficients[219] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[218]*/ mload(0x1f80), mulmod(/*coefficients[219]*/ mload(0x1fa0), /*adjustments[16]*/mload(0x4fc0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/y: ecdsa__signature0__exponentiate_generator__bit_0 * (column21_row23 + column21_row55) - column21_row15 * (column21_row7 - column21_row39). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_0*/ mload(0x43c0), addmod(/*column21_row23*/ mload(0x3bc0), /*column21_row55*/ mload(0x3c80), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row15*/ mload(0x3b20), addmod( /*column21_row7*/ mload(0x3a20), sub(PRIME, /*column21_row39*/ mload(0x3c60)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x4d60), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x48a0), PRIME) // res += val * (coefficients[220] + coefficients[221] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[220]*/ mload(0x1fc0), mulmod(/*coefficients[221]*/ mload(0x1fe0), /*adjustments[16]*/mload(0x4fc0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/add_points/x_diff_inv: column22_row0 * (column21_row7 - ecdsa__generator_points__x) - 1. let val := addmod( mulmod( /*column22_row0*/ mload(0x3e80), addmod( /*column21_row7*/ mload(0x3a20), sub(PRIME, /*periodic_column/ecdsa/generator_points/x*/ mload(0x40)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x4d60), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x48a0), PRIME) // res += val * (coefficients[222] + coefficients[223] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[222]*/ mload(0x2000), mulmod(/*coefficients[223]*/ mload(0x2020), /*adjustments[16]*/mload(0x4fc0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/x: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column21_row39 - column21_row7). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x43e0), addmod( /*column21_row39*/ mload(0x3c60), sub(PRIME, /*column21_row7*/ mload(0x3a20)), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x4d60), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x48a0), PRIME) // res += val * (coefficients[224] + coefficients[225] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[224]*/ mload(0x2040), mulmod(/*coefficients[225]*/ mload(0x2060), /*adjustments[16]*/mload(0x4fc0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_generator/copy_point/y: ecdsa__signature0__exponentiate_generator__bit_neg_0 * (column21_row55 - column21_row23). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_generator/bit_neg_0*/ mload(0x43e0), addmod( /*column21_row55*/ mload(0x3c80), sub(PRIME, /*column21_row23*/ mload(0x3bc0)), PRIME), PRIME) // Numerator: point^(trace_length / 8192) - trace_generator^(255 * trace_length / 256). // val *= numerators[8]. val := mulmod(val, mload(0x4d60), PRIME) // Denominator: point^(trace_length / 32) - 1. // val *= denominator_invs[14]. val := mulmod(val, mload(0x48a0), PRIME) // res += val * (coefficients[226] + coefficients[227] * adjustments[16]). res := addmod(res, mulmod(val, add(/*coefficients[226]*/ mload(0x2080), mulmod(/*coefficients[227]*/ mload(0x20a0), /*adjustments[16]*/mload(0x4fc0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/booleanity_test: ecdsa__signature0__exponentiate_key__bit_0 * (ecdsa__signature0__exponentiate_key__bit_0 - 1). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4400), addmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4400), sub(PRIME, 1), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[228] + coefficients[229] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[228]*/ mload(0x20c0), mulmod(/*coefficients[229]*/ mload(0x20e0), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/bit_extraction_end: column21_row3. let val := /*column21_row3*/ mload(0x39a0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - trace_generator^(251 * trace_length / 256). // val *= denominator_invs[17]. val := mulmod(val, mload(0x4900), PRIME) // res += val * (coefficients[230] + coefficients[231] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[230]*/ mload(0x2100), mulmod(/*coefficients[231]*/ mload(0x2120), /*adjustments[18]*/mload(0x5000), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/zeros_tail: column21_row3. let val := /*column21_row3*/ mload(0x39a0) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= denominator_invs[18]. val := mulmod(val, mload(0x4920), PRIME) // res += val * (coefficients[232] + coefficients[233] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[232]*/ mload(0x2140), mulmod(/*coefficients[233]*/ mload(0x2160), /*adjustments[18]*/mload(0x5000), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/slope: ecdsa__signature0__exponentiate_key__bit_0 * (column21_row5 - column21_row14) - column21_row13 * (column21_row9 - column21_row6). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4400), addmod( /*column21_row5*/ mload(0x39e0), sub(PRIME, /*column21_row14*/ mload(0x3b00)), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row13*/ mload(0x3ae0), addmod(/*column21_row9*/ mload(0x3a60), sub(PRIME, /*column21_row6*/ mload(0x3a00)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[234] + coefficients[235] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[234]*/ mload(0x2180), mulmod(/*coefficients[235]*/ mload(0x21a0), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x: column21_row13 * column21_row13 - ecdsa__signature0__exponentiate_key__bit_0 * (column21_row9 + column21_row6 + column21_row25). let val := addmod( mulmod(/*column21_row13*/ mload(0x3ae0), /*column21_row13*/ mload(0x3ae0), PRIME), sub( PRIME, mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4400), addmod( addmod(/*column21_row9*/ mload(0x3a60), /*column21_row6*/ mload(0x3a00), PRIME), /*column21_row25*/ mload(0x3c00), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[236] + coefficients[237] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[236]*/ mload(0x21c0), mulmod(/*coefficients[237]*/ mload(0x21e0), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/y: ecdsa__signature0__exponentiate_key__bit_0 * (column21_row5 + column21_row21) - column21_row13 * (column21_row9 - column21_row25). let val := addmod( mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_0*/ mload(0x4400), addmod(/*column21_row5*/ mload(0x39e0), /*column21_row21*/ mload(0x3b80), PRIME), PRIME), sub( PRIME, mulmod( /*column21_row13*/ mload(0x3ae0), addmod( /*column21_row9*/ mload(0x3a60), sub(PRIME, /*column21_row25*/ mload(0x3c00)), PRIME), PRIME)), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[238] + coefficients[239] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[238]*/ mload(0x2200), mulmod(/*coefficients[239]*/ mload(0x2220), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/add_points/x_diff_inv: column21_row11 * (column21_row9 - column21_row6) - 1. let val := addmod( mulmod( /*column21_row11*/ mload(0x3aa0), addmod(/*column21_row9*/ mload(0x3a60), sub(PRIME, /*column21_row6*/ mload(0x3a00)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[240] + coefficients[241] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[240]*/ mload(0x2240), mulmod(/*coefficients[241]*/ mload(0x2260), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/x: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column21_row25 - column21_row9). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x4420), addmod( /*column21_row25*/ mload(0x3c00), sub(PRIME, /*column21_row9*/ mload(0x3a60)), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[242] + coefficients[243] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[242]*/ mload(0x2280), mulmod(/*coefficients[243]*/ mload(0x22a0), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/exponentiate_key/copy_point/y: ecdsa__signature0__exponentiate_key__bit_neg_0 * (column21_row21 - column21_row5). let val := mulmod( /*intermediate_value/ecdsa/signature0/exponentiate_key/bit_neg_0*/ mload(0x4420), addmod( /*column21_row21*/ mload(0x3b80), sub(PRIME, /*column21_row5*/ mload(0x39e0)), PRIME), PRIME) // Numerator: point^(trace_length / 4096) - trace_generator^(255 * trace_length / 256). // val *= numerators[7]. val := mulmod(val, mload(0x4d40), PRIME) // Denominator: point^(trace_length / 16) - 1. // val *= denominator_invs[2]. val := mulmod(val, mload(0x4720), PRIME) // res += val * (coefficients[244] + coefficients[245] * adjustments[15]). res := addmod(res, mulmod(val, add(/*coefficients[244]*/ mload(0x22c0), mulmod(/*coefficients[245]*/ mload(0x22e0), /*adjustments[15]*/mload(0x4fa0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_gen/x: column21_row7 - ecdsa/sig_config.shift_point.x. let val := addmod( /*column21_row7*/ mload(0x3a20), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[246] + coefficients[247] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[246]*/ mload(0x2300), mulmod(/*coefficients[247]*/ mload(0x2320), /*adjustments[17]*/mload(0x4fe0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_gen/y: column21_row23 + ecdsa/sig_config.shift_point.y. let val := addmod( /*column21_row23*/ mload(0x3bc0), /*ecdsa/sig_config.shift_point.y*/ mload(0x300), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[248] + coefficients[249] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[248]*/ mload(0x2340), mulmod(/*coefficients[249]*/ mload(0x2360), /*adjustments[17]*/mload(0x4fe0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_key/x: column21_row9 - ecdsa/sig_config.shift_point.x. let val := addmod( /*column21_row9*/ mload(0x3a60), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x4960), PRIME) // res += val * (coefficients[250] + coefficients[251] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[250]*/ mload(0x2380), mulmod(/*coefficients[251]*/ mload(0x23a0), /*adjustments[18]*/mload(0x5000), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/init_key/y: column21_row5 - ecdsa/sig_config.shift_point.y. let val := addmod( /*column21_row5*/ mload(0x39e0), sub(PRIME, /*ecdsa/sig_config.shift_point.y*/ mload(0x300)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x4960), PRIME) // res += val * (coefficients[252] + coefficients[253] * adjustments[18]). res := addmod(res, mulmod(val, add(/*coefficients[252]*/ mload(0x23c0), mulmod(/*coefficients[253]*/ mload(0x23e0), /*adjustments[18]*/mload(0x5000), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/slope: column21_row8183 - (column21_row4085 + column22_row8160 * (column21_row8167 - column21_row4089)). let val := addmod( /*column21_row8183*/ mload(0x3e20), sub( PRIME, addmod( /*column21_row4085*/ mload(0x3ce0), mulmod( /*column22_row8160*/ mload(0x3ea0), addmod( /*column21_row8167*/ mload(0x3da0), sub(PRIME, /*column21_row4089*/ mload(0x3d00)), PRIME), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[254] + coefficients[255] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[254]*/ mload(0x2400), mulmod(/*coefficients[255]*/ mload(0x2420), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/x: column22_row8160 * column22_row8160 - (column21_row8167 + column21_row4089 + column21_row4102). let val := addmod( mulmod(/*column22_row8160*/ mload(0x3ea0), /*column22_row8160*/ mload(0x3ea0), PRIME), sub( PRIME, addmod( addmod(/*column21_row8167*/ mload(0x3da0), /*column21_row4089*/ mload(0x3d00), PRIME), /*column21_row4102*/ mload(0x3d60), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[256] + coefficients[257] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[256]*/ mload(0x2440), mulmod(/*coefficients[257]*/ mload(0x2460), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/y: column21_row8183 + column21_row4110 - column22_row8160 * (column21_row8167 - column21_row4102). let val := addmod( addmod(/*column21_row8183*/ mload(0x3e20), /*column21_row4110*/ mload(0x3d80), PRIME), sub( PRIME, mulmod( /*column22_row8160*/ mload(0x3ea0), addmod( /*column21_row8167*/ mload(0x3da0), sub(PRIME, /*column21_row4102*/ mload(0x3d60)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[258] + coefficients[259] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[258]*/ mload(0x2480), mulmod(/*coefficients[259]*/ mload(0x24a0), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/add_results/x_diff_inv: column21_row8175 * (column21_row8167 - column21_row4089) - 1. let val := addmod( mulmod( /*column21_row8175*/ mload(0x3dc0), addmod( /*column21_row8167*/ mload(0x3da0), sub(PRIME, /*column21_row4089*/ mload(0x3d00)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[260] + coefficients[261] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[260]*/ mload(0x24c0), mulmod(/*coefficients[261]*/ mload(0x24e0), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/slope: column21_row8181 + ecdsa/sig_config.shift_point.y - column21_row4093 * (column21_row8185 - ecdsa/sig_config.shift_point.x). let val := addmod( addmod( /*column21_row8181*/ mload(0x3e00), /*ecdsa/sig_config.shift_point.y*/ mload(0x300), PRIME), sub( PRIME, mulmod( /*column21_row4093*/ mload(0x3d40), addmod( /*column21_row8185*/ mload(0x3e40), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[262] + coefficients[263] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[262]*/ mload(0x2500), mulmod(/*coefficients[263]*/ mload(0x2520), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/x: column21_row4093 * column21_row4093 - (column21_row8185 + ecdsa/sig_config.shift_point.x + column21_row3). let val := addmod( mulmod(/*column21_row4093*/ mload(0x3d40), /*column21_row4093*/ mload(0x3d40), PRIME), sub( PRIME, addmod( addmod( /*column21_row8185*/ mload(0x3e40), /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0), PRIME), /*column21_row3*/ mload(0x39a0), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[264] + coefficients[265] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[264]*/ mload(0x2540), mulmod(/*coefficients[265]*/ mload(0x2560), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/extract_r/x_diff_inv: column21_row8189 * (column21_row8185 - ecdsa/sig_config.shift_point.x) - 1. let val := addmod( mulmod( /*column21_row8189*/ mload(0x3e60), addmod( /*column21_row8185*/ mload(0x3e40), sub(PRIME, /*ecdsa/sig_config.shift_point.x*/ mload(0x2e0)), PRIME), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[266] + coefficients[267] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[266]*/ mload(0x2580), mulmod(/*coefficients[267]*/ mload(0x25a0), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/z_nonzero: column21_row31 * column21_row4081 - 1. let val := addmod( mulmod(/*column21_row31*/ mload(0x3c40), /*column21_row4081*/ mload(0x3cc0), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[268] + coefficients[269] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[268]*/ mload(0x25c0), mulmod(/*coefficients[269]*/ mload(0x25e0), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/r_and_w_nonzero: column21_row3 * column21_row4091 - 1. let val := addmod( mulmod(/*column21_row3*/ mload(0x39a0), /*column21_row4091*/ mload(0x3d20), PRIME), sub(PRIME, 1), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 4096) - 1. // val *= denominator_invs[20]. val := mulmod(val, mload(0x4960), PRIME) // res += val * (coefficients[270] + coefficients[271] * adjustments[20]). res := addmod(res, mulmod(val, add(/*coefficients[270]*/ mload(0x2600), mulmod(/*coefficients[271]*/ mload(0x2620), /*adjustments[20]*/mload(0x5040), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/q_on_curve/x_squared: column21_row8177 - column21_row6 * column21_row6. let val := addmod( /*column21_row8177*/ mload(0x3de0), sub( PRIME, mulmod(/*column21_row6*/ mload(0x3a00), /*column21_row6*/ mload(0x3a00), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[272] + coefficients[273] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[272]*/ mload(0x2640), mulmod(/*coefficients[273]*/ mload(0x2660), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/signature0/q_on_curve/on_curve: column21_row14 * column21_row14 - (column21_row6 * column21_row8177 + ecdsa/sig_config.alpha * column21_row6 + ecdsa/sig_config.beta). let val := addmod( mulmod(/*column21_row14*/ mload(0x3b00), /*column21_row14*/ mload(0x3b00), PRIME), sub( PRIME, addmod( addmod( mulmod(/*column21_row6*/ mload(0x3a00), /*column21_row8177*/ mload(0x3de0), PRIME), mulmod(/*ecdsa/sig_config.alpha*/ mload(0x2c0), /*column21_row6*/ mload(0x3a00), PRIME), PRIME), /*ecdsa/sig_config.beta*/ mload(0x320), PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[274] + coefficients[275] * adjustments[19]). res := addmod(res, mulmod(val, add(/*coefficients[274]*/ mload(0x2680), mulmod(/*coefficients[275]*/ mload(0x26a0), /*adjustments[19]*/mload(0x5020), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/init_addr: column19_row22 - initial_ecdsa_addr. let val := addmod( /*column19_row22*/ mload(0x3560), sub(PRIME, /*initial_ecdsa_addr*/ mload(0x340)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[276] + coefficients[277] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[276]*/ mload(0x26c0), mulmod(/*coefficients[277]*/ mload(0x26e0), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/message_addr: column19_row4118 - (column19_row22 + 1). let val := addmod( /*column19_row4118*/ mload(0x3860), sub(PRIME, addmod(/*column19_row22*/ mload(0x3560), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[278] + coefficients[279] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[278]*/ mload(0x2700), mulmod(/*coefficients[279]*/ mload(0x2720), /*adjustments[17]*/mload(0x4fe0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/pubkey_addr: column19_row8214 - (column19_row4118 + 1). let val := addmod( /*column19_row8214*/ mload(0x38a0), sub(PRIME, addmod(/*column19_row4118*/ mload(0x3860), 1, PRIME)), PRIME) // Numerator: point - trace_generator^(8192 * (trace_length / 8192 - 1)). // val *= numerators[9]. val := mulmod(val, mload(0x4d80), PRIME) // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[280] + coefficients[281] * adjustments[21]). res := addmod(res, mulmod(val, add(/*coefficients[280]*/ mload(0x2740), mulmod(/*coefficients[281]*/ mload(0x2760), /*adjustments[21]*/mload(0x5060), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/message_value0: column19_row4119 - column21_row31. let val := addmod( /*column19_row4119*/ mload(0x3880), sub(PRIME, /*column21_row31*/ mload(0x3c40)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[282] + coefficients[283] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[282]*/ mload(0x2780), mulmod(/*coefficients[283]*/ mload(0x27a0), /*adjustments[17]*/mload(0x4fe0), PRIME)), PRIME), PRIME) } { // Constraint expression for ecdsa/pubkey_value0: column19_row23 - column21_row6. let val := addmod( /*column19_row23*/ mload(0x3580), sub(PRIME, /*column21_row6*/ mload(0x3a00)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 8192) - 1. // val *= denominator_invs[19]. val := mulmod(val, mload(0x4940), PRIME) // res += val * (coefficients[284] + coefficients[285] * adjustments[17]). res := addmod(res, mulmod(val, add(/*coefficients[284]*/ mload(0x27c0), mulmod(/*coefficients[285]*/ mload(0x27e0), /*adjustments[17]*/mload(0x4fe0), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_pc_init_addr: column19_row150 - initial_checkpoints_addr. let val := addmod( /*column19_row150*/ mload(0x36e0), sub(PRIME, /*initial_checkpoints_addr*/ mload(0x360)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - 1. // val *= denominator_invs[3]. val := mulmod(val, mload(0x4740), PRIME) // res += val * (coefficients[286] + coefficients[287] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[286]*/ mload(0x2800), mulmod(/*coefficients[287]*/ mload(0x2820), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_pc_final_addr: column19_row150 - final_checkpoints_addr. let val := addmod( /*column19_row150*/ mload(0x36e0), sub(PRIME, /*final_checkpoints_addr*/ mload(0x380)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= denominator_invs[21]. val := mulmod(val, mload(0x4980), PRIME) // res += val * (coefficients[288] + coefficients[289] * adjustments[4]). res := addmod(res, mulmod(val, add(/*coefficients[288]*/ mload(0x2840), mulmod(/*coefficients[289]*/ mload(0x2860), /*adjustments[4]*/mload(0x4e40), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/required_fp_addr: column19_row86 - (column19_row150 + 1). let val := addmod( /*column19_row86*/ mload(0x3620), sub(PRIME, addmod(/*column19_row150*/ mload(0x36e0), 1, PRIME)), PRIME) // Numerator: 1. // val *= 1. // val := mulmod(val, 1, PRIME). // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[290] + coefficients[291] * adjustments[10]). res := addmod(res, mulmod(val, add(/*coefficients[290]*/ mload(0x2880), mulmod(/*coefficients[291]*/ mload(0x28a0), /*adjustments[10]*/mload(0x4f00), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/required_pc_next_addr: (column19_row406 - column19_row150) * (column19_row406 - (column19_row150 + 2)). let val := mulmod( addmod( /*column19_row406*/ mload(0x3800), sub(PRIME, /*column19_row150*/ mload(0x36e0)), PRIME), addmod( /*column19_row406*/ mload(0x3800), sub(PRIME, addmod(/*column19_row150*/ mload(0x36e0), 2, PRIME)), PRIME), PRIME) // Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= numerators[10]. val := mulmod(val, mload(0x4da0), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[292] + coefficients[293] * adjustments[22]). res := addmod(res, mulmod(val, add(/*coefficients[292]*/ mload(0x28c0), mulmod(/*coefficients[293]*/ mload(0x28e0), /*adjustments[22]*/mload(0x5080), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_pc: (column19_row406 - column19_row150) * (column19_row151 - column19_row0). let val := mulmod( addmod( /*column19_row406*/ mload(0x3800), sub(PRIME, /*column19_row150*/ mload(0x36e0)), PRIME), addmod( /*column19_row151*/ mload(0x3700), sub(PRIME, /*column19_row0*/ mload(0x33c0)), PRIME), PRIME) // Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= numerators[10]. val := mulmod(val, mload(0x4da0), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[294] + coefficients[295] * adjustments[22]). res := addmod(res, mulmod(val, add(/*coefficients[294]*/ mload(0x2900), mulmod(/*coefficients[295]*/ mload(0x2920), /*adjustments[22]*/mload(0x5080), PRIME)), PRIME), PRIME) } { // Constraint expression for checkpoints/req_fp: (column19_row406 - column19_row150) * (column19_row87 - column21_row8). let val := mulmod( addmod( /*column19_row406*/ mload(0x3800), sub(PRIME, /*column19_row150*/ mload(0x36e0)), PRIME), addmod( /*column19_row87*/ mload(0x3640), sub(PRIME, /*column21_row8*/ mload(0x3a40)), PRIME), PRIME) // Numerator: point - trace_generator^(256 * (trace_length / 256 - 1)). // val *= numerators[10]. val := mulmod(val, mload(0x4da0), PRIME) // Denominator: point^(trace_length / 256) - 1. // val *= denominator_invs[11]. val := mulmod(val, mload(0x4840), PRIME) // res += val * (coefficients[296] + coefficients[297] * adjustments[22]). res := addmod(res, mulmod(val, add(/*coefficients[296]*/ mload(0x2940), mulmod(/*coefficients[297]*/ mload(0x2960), /*adjustments[22]*/mload(0x5080), PRIME)), PRIME), PRIME) } mstore(0, res) return(0, 0x20) } } } } contract CpuPublicInputOffsets { // The following constants are offsets of data expected in the public input. uint256 internal constant OFFSET_LOG_N_STEPS = 0; uint256 internal constant OFFSET_RC_MIN = 1; uint256 internal constant OFFSET_RC_MAX = 2; uint256 internal constant OFFSET_LAYOUT_CODE = 3; uint256 internal constant OFFSET_PROGRAM_BEGIN_ADDR = 4; uint256 internal constant OFFSET_PROGRAM_STOP_PTR = 5; uint256 internal constant OFFSET_EXECUTION_BEGIN_ADDR = 6; uint256 internal constant OFFSET_EXECUTION_STOP_PTR = 7; uint256 internal constant OFFSET_OUTPUT_BEGIN_ADDR = 8; uint256 internal constant OFFSET_OUTPUT_STOP_PTR = 9; uint256 internal constant OFFSET_PEDERSEN_BEGIN_ADDR = 10; uint256 internal constant OFFSET_PEDERSEN_STOP_PTR = 11; uint256 internal constant OFFSET_RANGE_CHECK_BEGIN_ADDR = 12; uint256 internal constant OFFSET_RANGE_CHECK_STOP_PTR = 13; uint256 internal constant OFFSET_ECDSA_BEGIN_ADDR = 14; uint256 internal constant OFFSET_ECDSA_STOP_PTR = 15; uint256 internal constant OFFSET_CHECKPOINTS_BEGIN_PTR = 16; uint256 internal constant OFFSET_CHECKPOINTS_STOP_PTR = 17; uint256 internal constant OFFSET_N_PUBLIC_MEMORY_PAGES = 18; uint256 internal constant OFFSET_PUBLIC_MEMORY = 19; uint256 internal constant N_WORDS_PER_PUBLIC_MEMORY_ENTRY = 2; // The format of the public input, starting at OFFSET_PUBLIC_MEMORY is as follows: // * For each page: // * First address in the page (this field is not included for the first page). // * Page size. // * Page hash. // * Padding cell address. // * Padding cell value. // # All data above this line, appears in the initial seed of the proof. // * For each page: // * Cumulative product. function getOffsetPageSize(uint256 pageId) internal pure returns (uint256) { return OFFSET_PUBLIC_MEMORY + 3 * pageId; } function getOffsetPageHash(uint256 pageId) internal pure returns (uint256) { return OFFSET_PUBLIC_MEMORY + 3 * pageId + 1; } function getOffsetPageAddr(uint256 pageId) internal pure returns (uint256) { require(pageId >= 1, "Address of page 0 is not part of the public input."); return OFFSET_PUBLIC_MEMORY + 3 * pageId - 1; } /* Returns the offset of the address of the padding cell. The offset of the padding cell value can be obtained by adding 1 to the result. */ function getOffsetPaddingCell(uint256 nPages) internal pure returns (uint256) { return OFFSET_PUBLIC_MEMORY + 3 * nPages - 1; } function getOffsetPageProd(uint256 pageId, uint256 nPages) internal pure returns (uint256) { return OFFSET_PUBLIC_MEMORY + 3 * nPages + 1 + pageId; } function getPublicInputLength(uint256 nPages) internal pure returns (uint256) { return OFFSET_PUBLIC_MEMORY + 4 * nPages + 1; } } contract PeriodicColumnContract { function compute(uint256 x) external pure returns(uint256 result); } contract IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns(bool); } contract IMerkleVerifier { uint256 constant internal MAX_N_MERKLE_VERIFIER_QUERIES = 128; function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash); } contract IQueryableFactRegistry is IFactRegistry { /* Returns true if at least one fact has been registered. */ function hasRegisteredFact() external view returns(bool); } contract IStarkVerifier { function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput ) internal view; } contract MemoryMap { /* We store the state of the verifer in a contiguous chunk of memory. The offsets of the different fields are listed below. E.g. The offset of the i'th hash is [mm_hashes + i]. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; uint256 constant internal MAX_N_QUERIES = 48; uint256 constant internal FRI_QUEUE_SIZE = MAX_N_QUERIES; uint256 constant internal MAX_SUPPORTED_MAX_FRI_STEP = 4; uint256 constant internal MM_EVAL_DOMAIN_SIZE = 0x0; uint256 constant internal MM_BLOW_UP_FACTOR = 0x1; uint256 constant internal MM_LOG_EVAL_DOMAIN_SIZE = 0x2; uint256 constant internal MM_PROOF_OF_WORK_BITS = 0x3; uint256 constant internal MM_EVAL_DOMAIN_GENERATOR = 0x4; uint256 constant internal MM_PUBLIC_INPUT_PTR = 0x5; uint256 constant internal MM_TRACE_COMMITMENT = 0x6; // uint256[2] uint256 constant internal MM_OODS_COMMITMENT = 0x8; uint256 constant internal MM_N_UNIQUE_QUERIES = 0x9; uint256 constant internal MM_CHANNEL = 0xa; // uint256[3] uint256 constant internal MM_MERKLE_QUEUE = 0xd; // uint256[96] uint256 constant internal MM_FRI_QUEUE = 0x6d; // uint256[144] uint256 constant internal MM_FRI_QUERIES_DELIMITER = 0xfd; uint256 constant internal MM_FRI_CTX = 0xfe; // uint256[40] uint256 constant internal MM_FRI_STEPS_PTR = 0x126; uint256 constant internal MM_FRI_EVAL_POINTS = 0x127; // uint256[10] uint256 constant internal MM_FRI_COMMITMENTS = 0x131; // uint256[10] uint256 constant internal MM_FRI_LAST_LAYER_DEG_BOUND = 0x13b; uint256 constant internal MM_FRI_LAST_LAYER_PTR = 0x13c; uint256 constant internal MM_CONSTRAINT_POLY_ARGS_START = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__PEDERSEN__POINTS__X = 0x13d; uint256 constant internal MM_PERIODIC_COLUMN__PEDERSEN__POINTS__Y = 0x13e; uint256 constant internal MM_PERIODIC_COLUMN__ECDSA__GENERATOR_POINTS__X = 0x13f; uint256 constant internal MM_PERIODIC_COLUMN__ECDSA__GENERATOR_POINTS__Y = 0x140; uint256 constant internal MM_TRACE_LENGTH = 0x141; uint256 constant internal MM_OFFSET_SIZE = 0x142; uint256 constant internal MM_HALF_OFFSET_SIZE = 0x143; uint256 constant internal MM_INITIAL_AP = 0x144; uint256 constant internal MM_INITIAL_PC = 0x145; uint256 constant internal MM_FINAL_AP = 0x146; uint256 constant internal MM_FINAL_PC = 0x147; uint256 constant internal MM_MEMORY__MULTI_COLUMN_PERM__PERM__INTERACTION_ELM = 0x148; uint256 constant internal MM_MEMORY__MULTI_COLUMN_PERM__HASH_INTERACTION_ELM0 = 0x149; uint256 constant internal MM_MEMORY__MULTI_COLUMN_PERM__PERM__PUBLIC_MEMORY_PROD = 0x14a; uint256 constant internal MM_RC16__PERM__INTERACTION_ELM = 0x14b; uint256 constant internal MM_RC16__PERM__PUBLIC_MEMORY_PROD = 0x14c; uint256 constant internal MM_RC_MIN = 0x14d; uint256 constant internal MM_RC_MAX = 0x14e; uint256 constant internal MM_PEDERSEN__SHIFT_POINT_X = 0x14f; uint256 constant internal MM_PEDERSEN__SHIFT_POINT_Y = 0x150; uint256 constant internal MM_INITIAL_PEDERSEN_ADDR = 0x151; uint256 constant internal MM_INITIAL_RC_ADDR = 0x152; uint256 constant internal MM_ECDSA__SIG_CONFIG_ALPHA = 0x153; uint256 constant internal MM_ECDSA__SIG_CONFIG_SHIFT_POINT_X = 0x154; uint256 constant internal MM_ECDSA__SIG_CONFIG_SHIFT_POINT_Y = 0x155; uint256 constant internal MM_ECDSA__SIG_CONFIG_BETA = 0x156; uint256 constant internal MM_INITIAL_ECDSA_ADDR = 0x157; uint256 constant internal MM_INITIAL_CHECKPOINTS_ADDR = 0x158; uint256 constant internal MM_FINAL_CHECKPOINTS_ADDR = 0x159; uint256 constant internal MM_TRACE_GENERATOR = 0x15a; uint256 constant internal MM_OODS_POINT = 0x15b; uint256 constant internal MM_INTERACTION_ELEMENTS = 0x15c; // uint256[3] uint256 constant internal MM_COEFFICIENTS = 0x15f; // uint256[298] uint256 constant internal MM_OODS_VALUES = 0x289; // uint256[174] uint256 constant internal MM_CONSTRAINT_POLY_ARGS_END = 0x337; uint256 constant internal MM_COMPOSITION_OODS_VALUES = 0x337; // uint256[2] uint256 constant internal MM_OODS_EVAL_POINTS = 0x339; // uint256[48] uint256 constant internal MM_OODS_COEFFICIENTS = 0x369; // uint256[176] uint256 constant internal MM_TRACE_QUERY_RESPONSES = 0x419; // uint256[1200] uint256 constant internal MM_COMPOSITION_QUERY_RESPONSES = 0x8c9; // uint256[96] uint256 constant internal MM_LOG_N_STEPS = 0x929; uint256 constant internal MM_N_PUBLIC_MEM_ENTRIES = 0x92a; uint256 constant internal MM_N_PUBLIC_MEM_PAGES = 0x92b; uint256 constant internal MM_CONTEXT_SIZE = 0x92c; } contract MemoryPageFactRegistryConstants { // A page based on a list of pairs (address, value). // In this case, memoryHash = hash(address, value, address, value, address, value, ...). uint256 internal constant REGULAR_PAGE = 0; // A page based on adjacent memory cells, starting from a given address. // In this case, memoryHash = hash(value, value, value, ...). uint256 internal constant CONTINUOUS_PAGE = 1; } contract MerkleStatementVerifier is IMerkleVerifier { MerkleStatementContract merkleStatementContract; constructor(address merkleStatementContractAddress) internal { merkleStatementContract = MerkleStatementContract(merkleStatementContractAddress); } // Computes the hash of the Merkle statement, and verifies that it is registered in the // Merkle Fact Registry. Receives as input the queuePtr (as address), its length // the numbers of queries n, and the root. The channelPtr is is ignored. function verify(uint256 /*channelPtr*/, uint256 queuePtr, bytes32 root, uint256 n) internal view returns(bytes32) { bytes32 statement; require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES"); assembly { let dataToHashPtrStart := mload(0x40) // freePtr. let dataToHashPtrCur := dataToHashPtrStart let queEndPtr := add(queuePtr, mul(n, 0x40)) for { } lt(queuePtr, queEndPtr) { } { mstore(dataToHashPtrCur, mload(queuePtr)) dataToHashPtrCur := add(dataToHashPtrCur, 0x20) queuePtr := add(queuePtr, 0x20) } mstore(dataToHashPtrCur, root) dataToHashPtrCur := add(dataToHashPtrCur, 0x20) mstore(0x40, dataToHashPtrCur) statement := keccak256(dataToHashPtrStart, sub(dataToHashPtrCur, dataToHashPtrStart)) } require(merkleStatementContract.isValid(statement), "INVALIDATED_MERKLE_STATEMENT"); return root; } } contract MerkleVerifier is IMerkleVerifier { function getHashMask() internal pure returns(uint256) { // Default implementation. return 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000; } /* Verifies a Merkle tree decommitment for n leaves in a Merkle tree with N leaves. The inputs data sits in the queue at queuePtr. Each slot in the queue contains a 32 bytes leaf index and a 32 byte leaf value. The indices need to be in the range [N..2*N-1] and strictly incrementing. Decommitments are read from the channel in the ctx. The input data is destroyed during verification. */ function verify( uint256 channelPtr, uint256 queuePtr, bytes32 root, uint256 n) internal view returns (bytes32 hash) { uint256 lhashMask = getHashMask(); require(n <= MAX_N_MERKLE_VERIFIER_QUERIES, "TOO_MANY_MERKLE_QUERIES"); assembly { // queuePtr + i * 0x40 gives the i'th index in the queue. // hashesPtr + i * 0x40 gives the i'th hash in the queue. let hashesPtr := add(queuePtr, 0x20) let queueSize := mul(n, 0x40) let slotSize := 0x40 // The items are in slots [0, n-1]. let rdIdx := 0 let wrIdx := 0 // = n % n. // Iterate the queue until we hit the root. let index := mload(add(rdIdx, queuePtr)) let proofPtr := mload(channelPtr) // while(index > 1). for { } gt(index, 1) { } { let siblingIndex := xor(index, 1) // sibblingOffset := 0x20 * lsb(siblingIndex). let sibblingOffset := mulmod(siblingIndex, 0x20, 0x40) // Store the hash corresponding to index in the correct slot. // 0 if index is even and 0x20 if index is odd. // The hash of the sibling will be written to the other slot. mstore(xor(0x20, sibblingOffset), mload(add(rdIdx, hashesPtr))) rdIdx := addmod(rdIdx, slotSize, queueSize) // Inline channel operation: // Assume we are going to read a new hash from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let newHashPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Push index/2 into the queue, before reading the next index. // The order is important, as otherwise we may try to read from an empty queue (in // the case where we are working on one item). // wrIdx will be updated after writing the relevant hash to the queue. mstore(add(wrIdx, queuePtr), div(index, 2)) // Load the next index from the queue and check if it is our sibling. index := mload(add(rdIdx, queuePtr)) if eq(index, siblingIndex) { // Take sibling from queue rather than from proof. newHashPtr := add(rdIdx, hashesPtr) // Revert reading from proof. proofPtr := sub(proofPtr, 0x20) rdIdx := addmod(rdIdx, slotSize, queueSize) // Index was consumed, read the next one. // Note that the queue can't be empty at this point. // The index of the parent of the current node was already pushed into the // queue, and the parent is never the sibling. index := mload(add(rdIdx, queuePtr)) } mstore(sibblingOffset, mload(newHashPtr)) // Push the new hash to the end of the queue. mstore(add(wrIdx, hashesPtr), and(lhashMask, keccak256(0x00, 0x40))) wrIdx := addmod(wrIdx, slotSize, queueSize) } hash := mload(add(rdIdx, hashesPtr)) // Update the proof pointer in the context. mstore(channelPtr, proofPtr) } // emit LogBool(hash == root); require(hash == root, "INVALID_MERKLE_PROOF"); } } contract PrimeFieldElement0 { uint256 constant internal K_MODULUS = 0x800000000000011000000000000000000000000000000000000000000000001; uint256 constant internal K_MODULUS_MASK = 0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant internal K_MONTGOMERY_R = 0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1; uint256 constant internal K_MONTGOMERY_R_INV = 0x40000000000001100000000000012100000000000000000000000000000000; uint256 constant internal GENERATOR_VAL = 3; uint256 constant internal ONE_VAL = 1; uint256 constant internal GEN1024_VAL = 0x659d83946a03edd72406af6711825f5653d9e35dc125289a206c054ec89c4f1; function fromMontgomery(uint256 val) internal pure returns (uint256 res) { // uint256 res = fmul(val, kMontgomeryRInv); assembly { res := mulmod(val, 0x40000000000001100000000000012100000000000000000000000000000000, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fromMontgomeryBytes(bytes32 bs) internal pure returns (uint256) { // Assuming bs is a 256bit bytes object, in Montgomery form, it is read into a field // element. uint256 res = uint256(bs); return fromMontgomery(res); } function toMontgomeryInt(uint256 val) internal pure returns (uint256 res) { //uint256 res = fmul(val, kMontgomeryR); assembly { res := mulmod(val, 0x7fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe1, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fmul(uint256 a, uint256 b) internal pure returns (uint256 res) { //uint256 res = mulmod(a, b, kModulus); assembly { res := mulmod(a, b, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fadd(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, b, kModulus); assembly { res := addmod(a, b, 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fsub(uint256 a, uint256 b) internal pure returns (uint256 res) { // uint256 res = addmod(a, kModulus - b, kModulus); assembly { res := addmod( a, sub(0x800000000000011000000000000000000000000000000000000000000000001, b), 0x800000000000011000000000000000000000000000000000000000000000001) } return res; } function fpow(uint256 val, uint256 exp) internal view returns (uint256) { return expmod(val, exp, K_MODULUS); } function expmod(uint256 base, uint256 exponent, uint256 modulus) internal view returns (uint256 res) { assembly { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(gas, 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } } function inverse(uint256 val) internal view returns (uint256) { return expmod(val, K_MODULUS - 2, K_MODULUS); } } contract Prng is PrimeFieldElement0 { function storePrng(uint256 statePtr, bytes32 digest, uint256 counter) internal pure { assembly { mstore(statePtr, digest) mstore(add(statePtr, 0x20), counter) } } function loadPrng(uint256 statePtr) internal pure returns (bytes32, uint256) { bytes32 digest; uint256 counter; assembly { digest := mload(statePtr) counter := mload(add(statePtr, 0x20)) } return (digest, counter); } function initPrng(uint256 prngPtr, bytes32 publicInputHash) internal pure { storePrng(prngPtr, /*keccak256(publicInput)*/ publicInputHash, 0); } /* Auxiliary function for getRandomBytes. */ function getRandomBytesInner(bytes32 digest, uint256 counter) internal pure returns (bytes32, uint256, bytes32) { // returns 32 bytes (for random field elements or four queries at a time). bytes32 randomBytes = keccak256(abi.encodePacked(digest, counter)); return (digest, counter + 1, randomBytes); } /* Returns 32 bytes. Used for a random field element, or for 4 query indices. */ function getRandomBytes(uint256 prngPtr) internal pure returns (bytes32 randomBytes) { bytes32 digest; uint256 counter; (digest, counter) = loadPrng(prngPtr); // returns 32 bytes (for random field elements or four queries at a time). (digest, counter, randomBytes) = getRandomBytesInner(digest, counter); storePrng(prngPtr, digest, counter); return randomBytes; } function mixSeedWithBytes(uint256 prngPtr, bytes memory dataBytes) internal pure { bytes32 digest; assembly { digest := mload(prngPtr) } initPrng(prngPtr, keccak256(abi.encodePacked(digest, dataBytes))); } function getPrngDigest(uint256 prngPtr) internal pure returns (bytes32 digest) { assembly { digest := mload(prngPtr) } } } contract StarkParameters is PrimeFieldElement0 { uint256 constant internal N_COEFFICIENTS = 298; uint256 constant internal N_INTERACTION_ELEMENTS = 3; uint256 constant internal MASK_SIZE = 174; uint256 constant internal N_ROWS_IN_MASK = 77; uint256 constant internal N_COLUMNS_IN_MASK = 25; uint256 constant internal N_COLUMNS_IN_TRACE0 = 23; uint256 constant internal N_COLUMNS_IN_TRACE1 = 2; uint256 constant internal CONSTRAINTS_DEGREE_BOUND = 2; uint256 constant internal N_OODS_VALUES = MASK_SIZE + CONSTRAINTS_DEGREE_BOUND; uint256 constant internal N_OODS_COEFFICIENTS = N_OODS_VALUES; uint256 constant internal MAX_FRI_STEP = 3; // ---------- // Air specific constants. ---------- uint256 constant internal PUBLIC_MEMORY_STEP = 8; uint256 constant internal PEDERSEN_BUILTIN_RATIO = 8; uint256 constant internal PEDERSEN_BUILTIN_REPETITIONS = 4; uint256 constant internal RC_BUILTIN_RATIO = 8; uint256 constant internal RC_N_PARTS = 8; uint256 constant internal ECDSA_BUILTIN_RATIO = 512; uint256 constant internal ECDSA_BUILTIN_REPETITIONS = 1; uint256 constant internal LAYOUT_CODE = 8098989891770344814; uint256 constant internal LOG_CPU_COMPONENT_HEIGHT = 4; } contract VerifierChannel is Prng { /* We store the state of the channel in uint256[3] as follows: [0] proof pointer. [1] prng digest. [2] prng counter. */ uint256 constant internal CHANNEL_STATE_SIZE = 3; event LogValue(bytes32 val); event SendRandomnessEvent(uint256 val); event ReadFieldElementEvent(uint256 val); event ReadHashEvent(bytes32 val); function getPrngPtr(uint256 channelPtr) internal pure returns (uint256) { return channelPtr + 0x20; } function initChannel(uint256 channelPtr, uint256 proofPtr, bytes32 publicInputHash) internal pure { assembly { // Skip 0x20 bytes length at the beginning of the proof. mstore(channelPtr, add(proofPtr, 0x20)) } initPrng(getPrngPtr(channelPtr), publicInputHash); } function sendFieldElements(uint256 channelPtr, uint256 nElements, uint256 targetPtr) internal pure { require(nElements < 0x1000000, "Overflow protection failed."); assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 let PRIME_MON_R_INV := 0x40000000000001100000000000012100000000000000000000000000000000 let PRIME_MASK := 0x0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff let digestPtr := add(channelPtr, 0x20) let counterPtr := add(channelPtr, 0x40) let endPtr := add(targetPtr, mul(nElements, 0x20)) for { } lt(targetPtr, endPtr) { targetPtr := add(targetPtr, 0x20) } { // *targetPtr = getRandomFieldElement(getPrngPtr(channelPtr)); let fieldElement := PRIME // while (fieldElement >= PRIME). for { } iszero(lt(fieldElement, PRIME)) { } { // keccak256(abi.encodePacked(digest, counter)); fieldElement := and(keccak256(digestPtr, 0x40), PRIME_MASK) // *counterPtr += 1; mstore(counterPtr, add(mload(counterPtr), 1)) } // *targetPtr = fromMontgomery(fieldElement); mstore(targetPtr, mulmod(fieldElement, PRIME_MON_R_INV, PRIME)) // emit ReadFieldElementEvent(fieldElement); // log1(targetPtr, 0x20, 0x4bfcc54f35095697be2d635fb0706801e13637312eff0cedcdfc254b3b8c385e); } } } /* Sends random queries and returns an array of queries sorted in ascending order. Generates count queries in the range [0, mask] and returns the number of unique queries. Note that mask is of the form 2^k-1 (for some k). Note that queriesOutPtr may be (and is) inteleaved with other arrays. The stride parameter is passed to indicate the distance between every two entries to the queries array, i.e. stride = 0x20*(number of interleaved arrays). */ function sendRandomQueries( uint256 channelPtr, uint256 count, uint256 mask, uint256 queriesOutPtr, uint256 stride) internal pure returns (uint256) { uint256 val; uint256 shift = 0; uint256 endPtr = queriesOutPtr; for (uint256 i = 0; i < count; i++) { if (shift == 0) { val = uint256(getRandomBytes(getPrngPtr(channelPtr))); shift = 0x100; } shift -= 0x40; uint256 queryIdx = (val >> shift) & mask; // emit sendRandomnessEvent(queryIdx); uint256 ptr = endPtr; uint256 curr; // Insert new queryIdx in the correct place like insertion sort. while (ptr > queriesOutPtr) { assembly { curr := mload(sub(ptr, stride)) } if (queryIdx >= curr) { break; } assembly { mstore(ptr, curr) } ptr -= stride; } if (queryIdx != curr) { assembly { mstore(ptr, queryIdx) } endPtr += stride; } else { // Revert right shuffling. while (ptr < endPtr) { assembly { mstore(ptr, mload(add(ptr, stride))) ptr := add(ptr, stride) } } } } return (endPtr - queriesOutPtr) / stride; } function readBytes(uint256 channelPtr, bool mix) internal pure returns (bytes32) { uint256 proofPtr; bytes32 val; assembly { proofPtr := mload(channelPtr) val := mload(proofPtr) mstore(channelPtr, add(proofPtr, 0x20)) } if (mix) { // inline: Prng.mixSeedWithBytes(getPrngPtr(channelPtr), abi.encodePacked(val)); assembly { let digestPtr := add(channelPtr, 0x20) let counterPtr := add(digestPtr, 0x20) mstore(counterPtr, val) // prng.digest := keccak256(digest||val), nonce was written earlier. mstore(digestPtr, keccak256(digestPtr, 0x40)) // prng.counter := 0. mstore(counterPtr, 0) } } return val; } function readHash(uint256 channelPtr, bool mix) internal pure returns (bytes32) { bytes32 val = readBytes(channelPtr, mix); // emit ReadHashEvent(val); return val; } function readFieldElement(uint256 channelPtr, bool mix) internal pure returns (uint256) { uint256 val = fromMontgomery(uint256(readBytes(channelPtr, mix))); // emit ReadFieldElementEvent(val); return val; } function verifyProofOfWork(uint256 channelPtr, uint256 proofOfWorkBits) internal pure { if (proofOfWorkBits == 0) { return; } uint256 proofOfWorkDigest; assembly { // [0:29] := 0123456789abcded || digest || workBits. mstore(0, 0x0123456789abcded000000000000000000000000000000000000000000000000) let digest := mload(add(channelPtr, 0x20)) mstore(0x8, digest) mstore8(0x28, proofOfWorkBits) mstore(0, keccak256(0, 0x29)) let proofPtr := mload(channelPtr) mstore(0x20, mload(proofPtr)) // proofOfWorkDigest:= keccak256(keccak256(0123456789abcded || digest || workBits) || nonce). proofOfWorkDigest := keccak256(0, 0x28) mstore(0, digest) // prng.digest := keccak256(digest||nonce), nonce was written earlier. mstore(add(channelPtr, 0x20), keccak256(0, 0x28)) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) mstore(channelPtr, add(proofPtr, 0x8)) } uint256 proofOfWorkThreshold = uint256(1) << (256 - proofOfWorkBits); require(proofOfWorkDigest < proofOfWorkThreshold, "Proof of work check failed."); } } contract FactRegistry is IQueryableFactRegistry { // Mapping: fact hash -> true. mapping (bytes32 => bool) private verifiedFact; // Indicates whether the Fact Registry has at least one fact registered. bool anyFactRegistered; /* Checks if a fact has been verified. */ function isValid(bytes32 fact) external view returns(bool) { return _factCheck(fact); } /* This is an internal method to check if the fact is already registered. In current implementation of FactRegistry it's identical to isValid(). But the check is against the local fact registry, So for a derived referral fact registry, it's not the same. */ function _factCheck(bytes32 fact) internal view returns(bool) { return verifiedFact[fact]; } function registerFact( bytes32 factHash ) internal { // This function stores the fact hash in the mapping. verifiedFact[factHash] = true; // Mark first time off. if (!anyFactRegistered) { anyFactRegistered = true; } } /* Indicates whether at least one fact was registered. */ function hasRegisteredFact() external view returns(bool) { return anyFactRegistered; } } contract FriLayer is MerkleVerifier, PrimeFieldElement0 { event LogGas(string name, uint256 val); uint256 constant internal FRI_MAX_FRI_STEP = 4; uint256 constant internal MAX_COSET_SIZE = 2**FRI_MAX_FRI_STEP; // Generator of the group of size MAX_COSET_SIZE: GENERATOR_VAL**((PRIME - 1)/MAX_COSET_SIZE). uint256 constant internal FRI_GROUP_GEN = 0x5ec467b88826aba4537602d514425f3b0bdf467bbf302458337c45f6021e539; uint256 constant internal FRI_GROUP_SIZE = 0x20 * MAX_COSET_SIZE; uint256 constant internal FRI_CTX_TO_COSET_EVALUATIONS_OFFSET = 0; uint256 constant internal FRI_CTX_TO_FRI_GROUP_OFFSET = FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET = FRI_CTX_TO_FRI_GROUP_OFFSET + FRI_GROUP_SIZE; uint256 constant internal FRI_CTX_SIZE = FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET + (FRI_GROUP_SIZE / 2); function nextLayerElementFromTwoPreviousLayerElements( uint256 fX, uint256 fMinusX, uint256 evalPoint, uint256 xInv) internal pure returns (uint256 res) { // Folding formula: // f(x) = g(x^2) + xh(x^2) // f(-x) = g((-x)^2) - xh((-x)^2) = g(x^2) - xh(x^2) // => // 2g(x^2) = f(x) + f(-x) // 2h(x^2) = (f(x) - f(-x))/x // => The 2*interpolation at evalPoint is: // 2*(g(x^2) + evalPoint*h(x^2)) = f(x) + f(-x) + evalPoint*(f(x) - f(-x))*xInv. // // Note that multiplying by 2 doesn't affect the degree, // so we can just agree to do that on both the prover and verifier. assembly { // PRIME is PrimeFieldElement0.K_MODULUS. let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 // Note that whenever we call add(), the result is always less than 2*PRIME, // so there are no overflows. res := addmod(add(fX, fMinusX), mulmod(mulmod(evalPoint, xInv, PRIME), add(fX, /*-fMinusX*/sub(PRIME, fMinusX)), PRIME), PRIME) } } /* Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element. FRI layer n: f0 f1 f2 f3 ----------------------------------------- \ / -- \ / ----------- FRI layer n+1: f0 f2 -------------------------------------------- \ ---/ ------------- FRI layer n+2: f0 The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements(). */ function do2FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let f0 := mload(evaluationsOnCosetPtr) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) f2 := addmod(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(mload(add(friHalfInvGroupPtr, 0x20)), friEvalPointDivByX, PRIME), PRIME), PRIME) } { let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME) nextXInv := mulmod(newXInv, newXInv, PRIME) } // f0 + f2 < 4P ( = 3 + 1). nextLayerValue := addmod(add(f0, f2), mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME), add(f0, /*-fMinusX*/sub(PRIME, f2)), PRIME), PRIME) } } /* Reads 8 elements, and applies 4 + 2 + 1 FRI transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do3FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 let MPRIME := 0x8000000000000110000000000000000000000000000000000000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0, f4 < 7P -> f0 + f4 < 14P && 9P < f0 + (MPRIME - f4) < 23P. nextLayerValue := addmod(add(f0, f4), mulmod(mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) nextXInv := mulmod(xInv4, xInv4, PRIME) } } } /* This function reads 16 elements, and applies 8 + 4 + 2 + 1 fri transformation to obtain a single element. See do2FriSteps for more detailed explanation. */ function do4FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let friEvalPointDivByXTessed let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 let MPRIME := 0x8000000000000110000000000000000000000000000000000000000000000010 let f0 := mload(evaluationsOnCosetPtr) let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME) let imaginaryUnit := mload(add(friHalfInvGroupPtr, 0x20)) { let f1 := mload(add(evaluationsOnCosetPtr, 0x20)) // f0 < 3P ( = 1 + 1 + 1). f0 := add(add(f0, f1), mulmod(friEvalPointDivByX, add(f0, /*-fMinusX*/sub(PRIME, f1)), PRIME)) } { let f2 := mload(add(evaluationsOnCosetPtr, 0x40)) { let f3 := mload(add(evaluationsOnCosetPtr, 0x60)) // f2 < 3P ( = 1 + 1 + 1). f2 := add(add(f2, f3), mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)), mulmod(friEvalPointDivByX, imaginaryUnit, PRIME), PRIME)) } { let friEvalPointDivByXSquared := mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME) friEvalPointDivByXTessed := mulmod(friEvalPointDivByXSquared, friEvalPointDivByXSquared, PRIME) // f0 < 7P ( = 3 + 3 + 1). f0 := add(add(f0, f2), mulmod(friEvalPointDivByXSquared, add(f0, /*-fMinusX*/sub(MPRIME, f2)), PRIME)) } } { let f4 := mload(add(evaluationsOnCosetPtr, 0x80)) { let friEvalPointDivByX2 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x40)), PRIME) { let f5 := mload(add(evaluationsOnCosetPtr, 0xa0)) // f4 < 3P ( = 1 + 1 + 1). f4 := add(add(f4, f5), mulmod(friEvalPointDivByX2, add(f4, /*-fMinusX*/sub(PRIME, f5)), PRIME)) } let f6 := mload(add(evaluationsOnCosetPtr, 0xc0)) { let f7 := mload(add(evaluationsOnCosetPtr, 0xe0)) // f6 < 3P ( = 1 + 1 + 1). f6 := add(add(f6, f7), mulmod(add(f6, /*-fMinusX*/sub(PRIME, f7)), // friEvalPointDivByX2 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0x60)). mulmod(friEvalPointDivByX2, imaginaryUnit, PRIME), PRIME)) } // f4 < 7P ( = 3 + 3 + 1). f4 := add(add(f4, f6), mulmod(mulmod(friEvalPointDivByX2, friEvalPointDivByX2, PRIME), add(f4, /*-fMinusX*/sub(MPRIME, f6)), PRIME)) } // f0 < 15P ( = 7 + 7 + 1). f0 := add(add(f0, f4), mulmod(friEvalPointDivByXTessed, add(f0, /*-fMinusX*/sub(MPRIME, f4)), PRIME)) } { let f8 := mload(add(evaluationsOnCosetPtr, 0x100)) { let friEvalPointDivByX4 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0x80)), PRIME) { let f9 := mload(add(evaluationsOnCosetPtr, 0x120)) // f8 < 3P ( = 1 + 1 + 1). f8 := add(add(f8, f9), mulmod(friEvalPointDivByX4, add(f8, /*-fMinusX*/sub(PRIME, f9)), PRIME)) } let f10 := mload(add(evaluationsOnCosetPtr, 0x140)) { let f11 := mload(add(evaluationsOnCosetPtr, 0x160)) // f10 < 3P ( = 1 + 1 + 1). f10 := add(add(f10, f11), mulmod(add(f10, /*-fMinusX*/sub(PRIME, f11)), // friEvalPointDivByX4 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xa0)). mulmod(friEvalPointDivByX4, imaginaryUnit, PRIME), PRIME)) } // f8 < 7P ( = 3 + 3 + 1). f8 := add(add(f8, f10), mulmod(mulmod(friEvalPointDivByX4, friEvalPointDivByX4, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f10)), PRIME)) } { let f12 := mload(add(evaluationsOnCosetPtr, 0x180)) { let friEvalPointDivByX6 := mulmod(friEvalPointDivByX, mload(add(friHalfInvGroupPtr, 0xc0)), PRIME) { let f13 := mload(add(evaluationsOnCosetPtr, 0x1a0)) // f12 < 3P ( = 1 + 1 + 1). f12 := add(add(f12, f13), mulmod(friEvalPointDivByX6, add(f12, /*-fMinusX*/sub(PRIME, f13)), PRIME)) } let f14 := mload(add(evaluationsOnCosetPtr, 0x1c0)) { let f15 := mload(add(evaluationsOnCosetPtr, 0x1e0)) // f14 < 3P ( = 1 + 1 + 1). f14 := add(add(f14, f15), mulmod(add(f14, /*-fMinusX*/sub(PRIME, f15)), // friEvalPointDivByX6 * imaginaryUnit == // friEvalPointDivByX * mload(add(friHalfInvGroupPtr, 0xe0)). mulmod(friEvalPointDivByX6, imaginaryUnit, PRIME), PRIME)) } // f12 < 7P ( = 3 + 3 + 1). f12 := add(add(f12, f14), mulmod(mulmod(friEvalPointDivByX6, friEvalPointDivByX6, PRIME), add(f12, /*-fMinusX*/sub(MPRIME, f14)), PRIME)) } // f8 < 15P ( = 7 + 7 + 1). f8 := add(add(f8, f12), mulmod(mulmod(friEvalPointDivByXTessed, imaginaryUnit, PRIME), add(f8, /*-fMinusX*/sub(MPRIME, f12)), PRIME)) } // f0, f8 < 15P -> f0 + f8 < 30P && 16P < f0 + (MPRIME - f8) < 31P. nextLayerValue := addmod(add(f0, f8), mulmod(mulmod(friEvalPointDivByXTessed, friEvalPointDivByXTessed, PRIME), add(f0, /*-fMinusX*/sub(MPRIME, f8)), PRIME), PRIME) } { let xInv2 := mulmod(cosetOffset_, cosetOffset_, PRIME) let xInv4 := mulmod(xInv2, xInv2, PRIME) let xInv8 := mulmod(xInv4, xInv4, PRIME) nextXInv := mulmod(xInv8, xInv8, PRIME) } } } /* Gathers the "cosetSize" elements that belong to the same coset as the item at the top of the FRI queue and stores them in ctx[MM_FRI_STEP_VALUES:]. Returns friQueueHead - friQueueHead_ + 0x60 * (# elements that were taken from the queue). cosetIdx - the start index of the coset that was gathered. cosetOffset_ - the xInv field element that corresponds to cosetIdx. */ function gatherCosetInputs( uint256 channelPtr, uint256 friCtx, uint256 friQueueHead_, uint256 cosetSize) internal pure returns (uint256 friQueueHead, uint256 cosetIdx, uint256 cosetOffset_) { uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; friQueueHead = friQueueHead_; assembly { let queueItemIdx := mload(friQueueHead) // The coset index is represented by the most significant bits of the queue item index. cosetIdx := and(queueItemIdx, not(sub(cosetSize, 1))) let nextCosetIdx := add(cosetIdx, cosetSize) let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 // Get the algebraic coset offset: // I.e. given c*g^(-k) compute c, where // g is the generator of the coset group. // k is bitReverse(offsetWithinCoset, log2(cosetSize)). // // To do this we multiply the algebraic coset offset at the top of the queue (c*g^(-k)) // by the group element that corresponds to the index inside the coset (g^k). cosetOffset_ := mulmod( /*(c*g^(-k)*/ mload(add(friQueueHead, 0x40)), /*(g^k)*/ mload(add(friGroupPtr, mul(/*offsetWithinCoset*/sub(queueItemIdx, cosetIdx), 0x20))), PRIME) let proofPtr := mload(channelPtr) for { let index := cosetIdx } lt(index, nextCosetIdx) { index := add(index, 1) } { // Inline channel operation: // Assume we are going to read the next element from the proof. // If this is not the case add(proofPtr, 0x20) will be reverted. let fieldElementPtr := proofPtr proofPtr := add(proofPtr, 0x20) // Load the next index from the queue and check if it is our sibling. if eq(index, queueItemIdx) { // Take element from the queue rather than from the proof // and convert it back to Montgomery form for Merkle verification. fieldElementPtr := add(friQueueHead, 0x20) // Revert the read from proof. proofPtr := sub(proofPtr, 0x20) // Reading the next index here is safe due to the // delimiter after the queries. friQueueHead := add(friQueueHead, 0x60) queueItemIdx := mload(friQueueHead) } // Note that we apply the modulo operation to convert the field elements we read // from the proof to canonical representation (in the range [0, PRIME - 1]). mstore(evaluationsOnCosetPtr, mod(mload(fieldElementPtr), PRIME)) evaluationsOnCosetPtr := add(evaluationsOnCosetPtr, 0x20) } mstore(channelPtr, proofPtr) } } /* Returns the bit reversal of num assuming it has the given number of bits. For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101, the function will return (0b)101100. */ function bitReverse(uint256 num, uint256 numberOfBits) internal pure returns(uint256 numReversed) { assert((numberOfBits == 256) || (num < 2 ** numberOfBits)); uint256 n = num; uint256 r = 0; for (uint256 k = 0; k < numberOfBits; k++) { r = (r * 2) | (n % 2); n = n / 2; } return r; } /* Initializes the FRI group and half inv group in the FRI context. */ function initFriGroups(uint256 friCtx) internal view { uint256 friGroupPtr = friCtx + FRI_CTX_TO_FRI_GROUP_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // FRI_GROUP_GEN is the coset generator. // Raising it to the (MAX_COSET_SIZE - 1) power gives us the inverse. uint256 genFriGroup = FRI_GROUP_GEN; uint256 genFriGroupInv = fpow(genFriGroup, (MAX_COSET_SIZE - 1)); uint256 lastVal = ONE_VAL; uint256 lastValInv = ONE_VAL; uint256 prime = PrimeFieldElement0.K_MODULUS; assembly { // ctx[mmHalfFriInvGroup + 0] = ONE_VAL; mstore(friHalfInvGroupPtr, lastValInv) // ctx[mmFriGroup + 0] = ONE_VAL; mstore(friGroupPtr, lastVal) // ctx[mmFriGroup + 1] = fsub(0, ONE_VAL); mstore(add(friGroupPtr, 0x20), sub(prime, lastVal)) } // To compute [1, -1 (== g^n/2), g^n/4, -g^n/4, ...] // we compute half the elements and derive the rest using negation. uint256 halfCosetSize = MAX_COSET_SIZE / 2; for (uint256 i = 1; i < halfCosetSize; i++) { lastVal = fmul(lastVal, genFriGroup); lastValInv = fmul(lastValInv, genFriGroupInv); uint256 idx = bitReverse(i, FRI_MAX_FRI_STEP-1); assembly { // ctx[mmHalfFriInvGroup + idx] = lastValInv; mstore(add(friHalfInvGroupPtr, mul(idx, 0x20)), lastValInv) // ctx[mmFriGroup + 2*idx] = lastVal; mstore(add(friGroupPtr, mul(idx, 0x40)), lastVal) // ctx[mmFriGroup + 2*idx + 1] = fsub(0, lastVal); mstore(add(friGroupPtr, add(mul(idx, 0x40), 0x20)), sub(prime, lastVal)) } } } /* Operates on the coset of size friFoldedCosetSize that start at index. It produces 3 outputs: 1. The field elements that result from doing FRI reductions on the coset. 2. The pointInv elements for the location that corresponds to the first output. 3. The root of a Merkle tree for the input layer. The input is read either from the queue or from the proof depending on data availability. Since the function reads from the queue it returns an updated head pointer. */ function doFriSteps( uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint, uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr) internal pure { uint256 friValue; uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET; uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET; // Compare to expected FRI step sizes in order of likelihood, step size 3 being most common. if (friCosetSize == 8) { (friValue, cosetOffset_) = do3FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 4) { (friValue, cosetOffset_) = do2FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else if (friCosetSize == 16) { (friValue, cosetOffset_) = do4FriSteps( friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint); } else { require(false, "Only step sizes of 2, 3 or 4 are supported."); } uint256 lhashMask = getHashMask(); assembly { let indexInNextStep := div(index, friCosetSize) mstore(merkleQueuePtr, indexInNextStep) mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr, mul(0x20,friCosetSize)))) mstore(friQueueTail, indexInNextStep) mstore(add(friQueueTail, 0x20), friValue) mstore(add(friQueueTail, 0x40), cosetOffset_) } } /* Computes the FRI step with eta = log2(friCosetSize) for all the live queries. The input and output data is given in array of triplets: (query index, FRI value, FRI inversed point) in the address friQueuePtr (which is &ctx[mmFriQueue:]). The function returns the number of live queries remaining after computing the FRI step. The number of live queries decreases whenever multiple query points in the same coset are reduced to a single query in the next FRI layer. As the function computes the next layer it also collects that data from the previous layer for Merkle verification. */ function computeNextLayer( uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries, uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx) internal pure returns (uint256 nLiveQueries) { uint256 merkleQueueTail = merkleQueuePtr; uint256 friQueueHead = friQueuePtr; uint256 friQueueTail = friQueuePtr; uint256 friQueueEnd = friQueueHead + (0x60 * nQueries); do { uint256 cosetOffset; uint256 index; (friQueueHead, index, cosetOffset) = gatherCosetInputs( channelPtr, friCtx, friQueueHead, friCosetSize); doFriSteps( friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index, merkleQueueTail); merkleQueueTail += 0x40; friQueueTail += 0x60; } while (friQueueHead < friQueueEnd); return (friQueueTail - friQueuePtr) / 0x60; } } contract FriStatementContract is FriLayer, FactRegistry { /* Compute a single FRI layer of size friStepSize at evaluationPoint starting from input friQueue, and the extra witnesses in the "proof" channel. Also check that the input and witnesses belong to a Merkle tree with root expectedRoot, again using witnesses from "proof". After verification, register the FRI fact hash, which is: keccak256( evaluationPoint, friStepSize, keccak256(friQueue_input), keccak256(friQueue_output), // The FRI queue after proccessing the FRI layer expectedRoot ) Note that this function is used as external, but declared public to avoid copying the arrays. */ function verifyFRI( uint256[] memory proof, uint256[] memory friQueue, uint256 evaluationPoint, uint256 friStepSize, uint256 expectedRoot) public { require (friStepSize <= FRI_MAX_FRI_STEP, "FRI step size too large"); /* The friQueue should have of 3*nQueries + 1 elements, beginning with nQueries triplets of the form (query_index, FRI_value, FRI_inverse_point), and ending with a single buffer cell set to 0, which is accessed and read during the computation of the FRI layer. */ require ( friQueue.length % 3 == 1, "FRI Queue must be composed of triplets plus one delimiter cell"); require (friQueue.length >= 4, "No query to process"); uint256 mmFriCtxSize = FRI_CTX_SIZE; uint256 nQueries = friQueue.length / 3; friQueue[3*nQueries] = 0; // NOLINT: divide-before-multiply. uint256 merkleQueuePtr; uint256 friQueuePtr; uint256 channelPtr; uint256 friCtx; uint256 dataToHash; // Verify evaluation point within valid range. require(evaluationPoint < K_MODULUS, "INVALID_EVAL_POINT"); // Queries need to be in the range [2**height .. 2**(height+1)-1] strictly incrementing. // i.e. we need to check that Qi+1 > Qi for each i, // but regarding the height range - it's sufficient to check that // (Q1 ^ Qn) < Q1 Which affirms that all queries are within the same logarithmic step. // Verify FRI values and inverses are within valid range. // and verify that queries are strictly incrementing. uint256 prevQuery = 0; // If we pass height, change to: prevQuery = 1 << height - 1; for (uint256 i = 0; i < nQueries; i++) { require(friQueue[3*i] > prevQuery, "INVALID_QUERY_VALUE"); require(friQueue[3*i+1] < K_MODULUS, "INVALID_FRI_VALUE"); require(friQueue[3*i+2] < K_MODULUS, "INVALID_FRI_INVERSE_POINT"); prevQuery = friQueue[3*i]; } // Verify all queries are on the same logarithmic step. // NOLINTNEXTLINE: divide-before-multiply. require((friQueue[0] ^ friQueue[3*nQueries-3]) < friQueue[0], "INVALID_QUERIES_RANGE"); // Allocate memory queues: channelPtr, merkleQueue, friCtx, dataToHash. assembly { friQueuePtr := add(friQueue, 0x20) channelPtr := mload(0x40) // Free pointer location. mstore(channelPtr, add(proof, 0x20)) merkleQueuePtr := add(channelPtr, 0x20) friCtx := add(merkleQueuePtr, mul(0x40, nQueries)) dataToHash := add(friCtx, mmFriCtxSize) mstore(0x40, add(dataToHash, 0xa0)) // Advance free pointer. mstore(dataToHash, evaluationPoint) mstore(add(dataToHash, 0x20), friStepSize) mstore(add(dataToHash, 0x80), expectedRoot) // Hash FRI inputs and add to dataToHash. mstore(add(dataToHash, 0x40), keccak256(friQueuePtr, mul(0x60, nQueries))) } initFriGroups(friCtx); nQueries = computeNextLayer( channelPtr, friQueuePtr, merkleQueuePtr, nQueries, evaluationPoint, 2**friStepSize, /* friCosetSize = 2**friStepSize */ friCtx); verify(channelPtr, merkleQueuePtr, bytes32(expectedRoot), nQueries); bytes32 factHash; assembly { // Hash FRI outputs and add to dataToHash. mstore(add(dataToHash, 0x60), keccak256(friQueuePtr, mul(0x60, nQueries))) factHash := keccak256(dataToHash, 0xa0) } registerFact(factHash); } } contract HornerEvaluator is PrimeFieldElement0 { /* Computes the evaluation of a polynomial f(x) = sum(a_i * x^i) on the given point. The coefficients of the polynomial are given in a_0 = coefsStart[0], ..., a_{n-1} = coefsStart[n - 1] where n = nCoefs = friLastLayerDegBound. Note that coefsStart is not actually an array but a direct pointer. The function requires that n is divisible by 8. */ function hornerEval(uint256 coefsStart, uint256 point, uint256 nCoefs) internal pure returns (uint256) { uint256 result = 0; uint256 prime = PrimeFieldElement0.K_MODULUS; require(nCoefs % 8 == 0, "Number of polynomial coefficients must be divisible by 8"); require(nCoefs < 4096, "No more than 4096 coefficients are supported"); assembly { let coefsPtr := add(coefsStart, mul(nCoefs, 0x20)) for { } gt(coefsPtr, coefsStart) { } { // Reduce coefsPtr by 8 field elements. coefsPtr := sub(coefsPtr, 0x100) // Apply 4 Horner steps (result := result * point + coef). result := add(mload(add(coefsPtr, 0x80)), mulmod( add(mload(add(coefsPtr, 0xa0)), mulmod( add(mload(add(coefsPtr, 0xc0)), mulmod( add(mload(add(coefsPtr, 0xe0)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) // Apply 4 additional Horner steps. result := add(mload(coefsPtr), mulmod( add(mload(add(coefsPtr, 0x20)), mulmod( add(mload(add(coefsPtr, 0x40)), mulmod( add(mload(add(coefsPtr, 0x60)), mulmod( result, point, prime)), point, prime)), point, prime)), point, prime)) } } // Since the last operation was "add" (instead of "addmod"), we need to take result % prime. return result % prime; } } contract MemoryAccessUtils is MemoryMap { function getPtr(uint256[] memory ctx, uint256 offset) internal pure returns (uint256) { uint256 ctxPtr; require(offset < MM_CONTEXT_SIZE, "Overflow protection failed"); assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + offset * 0x20; } function getProofPtr(uint256[] memory proof) internal pure returns (uint256) { uint256 proofPtr; assembly { proofPtr := proof } return proofPtr; } function getChannelPtr(uint256[] memory ctx) internal pure returns (uint256) { uint256 ctxPtr; assembly { ctxPtr := add(ctx, 0x20) } return ctxPtr + MM_CHANNEL * 0x20; } function getQueries(uint256[] memory ctx) internal pure returns (uint256[] memory) { uint256[] memory queries; // Dynamic array holds length followed by values. uint256 offset = 0x20 + 0x20*MM_N_UNIQUE_QUERIES; assembly { queries := add(ctx, offset) } return queries; } function getMerkleQueuePtr(uint256[] memory ctx) internal pure returns (uint256) { return getPtr(ctx, MM_MERKLE_QUEUE); } function getFriSteps(uint256[] memory ctx) internal pure returns (uint256[] memory friSteps) { uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { friSteps := mload(friStepsPtr) } } } contract MemoryPageFactRegistry is FactRegistry, MemoryPageFactRegistryConstants { event LogMemoryPageFact(bytes32 factHash, uint256 memoryHash, uint256 prod); /* Registers a fact based of the given memory (address, value) pairs (REGULAR_PAGE). */ function registerRegularMemoryPage( uint256[] calldata memoryPairs, uint256 z, uint256 alpha, uint256 prime) external returns (bytes32 factHash, uint256 memoryHash, uint256 prod) { require(memoryPairs.length < 2**20, "Too many memory values."); require(memoryPairs.length % 2 == 0, "Size of memoryPairs must be even."); require(z < prime, "Invalid value of z."); require(alpha < prime, "Invalid value of alpha."); (factHash, memoryHash, prod) = computeFactHash(memoryPairs, z, alpha, prime); emit LogMemoryPageFact(factHash, memoryHash, prod); registerFact(factHash); } function computeFactHash( uint256[] memory memoryPairs, uint256 z, uint256 alpha, uint256 prime) internal pure returns (bytes32 factHash, uint256 memoryHash, uint256 prod) { uint256 memorySize = memoryPairs.length / 2; prod = 1; assembly { let memoryPtr := add(memoryPairs, 0x20) // Each value of memoryPairs is a pair: (address, value). let lastPtr := add(memoryPtr, mul(memorySize, 0x40)) for { let ptr := memoryPtr } lt(ptr, lastPtr) { ptr := add(ptr, 0x40) } { // Compute address + alpha * value. let address_value_lin_comb := addmod( /*address*/ mload(ptr), mulmod(/*value*/ mload(add(ptr, 0x20)), alpha, prime), prime) prod := mulmod(prod, add(z, sub(prime, address_value_lin_comb)), prime) } memoryHash := keccak256(memoryPtr, mul(/*0x20 * 2*/ 0x40, memorySize)) } factHash = keccak256( abi.encodePacked( REGULAR_PAGE, prime, memorySize, z, alpha, prod, memoryHash, uint256(0)) ); } /* Registers a fact based on the given values, assuming continuous addresses. values should be [value at startAddr, value at (startAddr + 1), ...]. */ function registerContinuousMemoryPage( // NOLINT: external-function. uint256 startAddr, uint256[] memory values, uint256 z, uint256 alpha, uint256 prime) public returns (bytes32 factHash, uint256 memoryHash, uint256 prod) { require(values.length < 2**20, "Too many memory values."); require(prime < 2**254, "prime is too big for the optimizations in this function."); require(z < prime, "Invalid value of z."); require(alpha < prime, "Invalid value of alpha."); require(startAddr < 2**64 && startAddr < prime, "Invalid value of startAddr."); uint256 nValues = values.length; assembly { // Initialize prod to 1. prod := 1 // Initialize valuesPtr to point to the first value in the array. let valuesPtr := add(values, 0x20) let minus_z := mod(sub(prime, z), prime) // Start by processing full batches of 8 cells, addr represents the last address in each // batch. let addr := add(startAddr, 7) let lastAddr := add(startAddr, nValues) for {} lt(addr, lastAddr) { addr := add(addr, 8) } { // Compute the product of (lin_comb - z) instead of (z - lin_comb), since we're // doing an even number of iterations, the result is the same. prod := mulmod(prod, mulmod(add(add(sub(addr, 7), mulmod( mload(valuesPtr), alpha, prime)), minus_z), add(add(sub(addr, 6), mulmod( mload(add(valuesPtr, 0x20)), alpha, prime)), minus_z), prime), prime) prod := mulmod(prod, mulmod(add(add(sub(addr, 5), mulmod( mload(add(valuesPtr, 0x40)), alpha, prime)), minus_z), add(add(sub(addr, 4), mulmod( mload(add(valuesPtr, 0x60)), alpha, prime)), minus_z), prime), prime) prod := mulmod(prod, mulmod(add(add(sub(addr, 3), mulmod( mload(add(valuesPtr, 0x80)), alpha, prime)), minus_z), add(add(sub(addr, 2), mulmod( mload(add(valuesPtr, 0xa0)), alpha, prime)), minus_z), prime), prime) prod := mulmod(prod, mulmod(add(add(sub(addr, 1), mulmod( mload(add(valuesPtr, 0xc0)), alpha, prime)), minus_z), add(add(addr, mulmod( mload(add(valuesPtr, 0xe0)), alpha, prime)), minus_z), prime), prime) valuesPtr := add(valuesPtr, 0x100) } // Handle leftover. // Translate addr to the beginning of the last incomplete batch. addr := sub(addr, 7) for {} lt(addr, lastAddr) { addr := add(addr, 1) } { let address_value_lin_comb := addmod( addr, mulmod(mload(valuesPtr), alpha, prime), prime) prod := mulmod(prod, add(z, sub(prime, address_value_lin_comb)), prime) valuesPtr := add(valuesPtr, 0x20) } memoryHash := keccak256(add(values, 0x20), mul(0x20, nValues)) } factHash = keccak256( abi.encodePacked( CONTINUOUS_PAGE, prime, nValues, z, alpha, prod, memoryHash, startAddr) ); emit LogMemoryPageFact(factHash, memoryHash, prod); registerFact(factHash); } } contract MerkleStatementContract is MerkleVerifier, FactRegistry { /* This function recieves an initial merkle queue (consists of indices of leaves in the merkle in addition to their values) and a merkle view (contains the values of all the nodes required to be able to validate the queue). In case of success it registers the Merkle fact, which is the hash of the queue together with the resulting root. */ // NOLINTNEXTLINE: external-function. function verifyMerkle( uint256[] memory merkleView, uint256[] memory initialMerkleQueue, uint256 height, uint256 expectedRoot ) public { require(height < 200, "Height must be < 200."); require( initialMerkleQueue.length <= MAX_N_MERKLE_VERIFIER_QUERIES * 2, "TOO_MANY_MERKLE_QUERIES"); uint256 merkleQueuePtr; uint256 channelPtr; uint256 nQueries; uint256 dataToHashPtr; uint256 badInput = 0; assembly { // Skip 0x20 bytes length at the beginning of the merkleView. let merkleViewPtr := add(merkleView, 0x20) // Let channelPtr point to a free space. channelPtr := mload(0x40) // freePtr. // channelPtr will point to the merkleViewPtr since the 'verify' function expects // a pointer to the proofPtr. mstore(channelPtr, merkleViewPtr) // Skip 0x20 bytes length at the beginning of the initialMerkleQueue. merkleQueuePtr := add(initialMerkleQueue, 0x20) // Get number of queries. nQueries := div(mload(initialMerkleQueue), 0x2) // Get a pointer to the end of initialMerkleQueue. let initialMerkleQueueEndPtr := add(merkleQueuePtr, mul(nQueries, 0x40)) // Let dataToHashPtr point to a free memory. dataToHashPtr := add(channelPtr, 0x20) // Next freePtr. // Copy initialMerkleQueue to dataToHashPtr and validaite the indices. // The indices need to be in the range [2**height..2*(height+1)-1] and // strictly incrementing. // First index needs to be >= 2**height. let idxLowerLimit := shl(height, 1) for { } lt(merkleQueuePtr, initialMerkleQueueEndPtr) { } { let curIdx := mload(merkleQueuePtr) // badInput |= curIdx < IdxLowerLimit. badInput := or(badInput, lt(curIdx, idxLowerLimit)) // The next idx must be at least curIdx + 1. idxLowerLimit := add(curIdx, 1) // Copy the pair (idx, hash) to the dataToHash array. mstore(dataToHashPtr, curIdx) mstore(add(dataToHashPtr, 0x20), mload(add(merkleQueuePtr, 0x20))) dataToHashPtr := add(dataToHashPtr, 0x40) merkleQueuePtr := add(merkleQueuePtr, 0x40) } // We need to enforce that lastIdx < 2**(height+1) // => fail if lastIdx >= 2**(height+1) // => fail if (lastIdx + 1) > 2**(height+1) // => fail if idxLowerLimit > 2**(height+1). badInput := or(badInput, gt(idxLowerLimit, shl(height, 2))) // Reset merkleQueuePtr. merkleQueuePtr := add(initialMerkleQueue, 0x20) // Let freePtr point to a free memory (one word after the copied queries - reserved // for the root). mstore(0x40, add(dataToHashPtr, 0x20)) } require(badInput == 0, "INVALID_MERKLE_INDICES"); bytes32 resRoot = verify(channelPtr, merkleQueuePtr, bytes32(expectedRoot), nQueries); bytes32 factHash; assembly { // Append the resulted root (should be the return value of verify) to dataToHashPtr. mstore(dataToHashPtr, resRoot) // Reset dataToHashPtr. dataToHashPtr := add(channelPtr, 0x20) factHash := keccak256(dataToHashPtr, add(mul(nQueries, 0x40), 0x20)) } registerFact(factHash); } } contract Fri is MemoryMap, MemoryAccessUtils, HornerEvaluator, FriLayer { event LogGas(string name, uint256 val); function verifyLastLayer(uint256[] memory ctx, uint256 nPoints) internal view { uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1; uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR]; for (uint256 i = 0; i < nPoints; i++) { uint256 point = ctx[MM_FRI_QUEUE + 3*i + 2]; // Invert point using inverse(point) == fpow(point, ord(point) - 1). point = fpow(point, groupOrderMinusOne); require( hornerEval(coefsStart, point, friLastLayerDegBound) == ctx[MM_FRI_QUEUE + 3*i + 1], "Bad Last layer value."); } } /* Verifies FRI layers. Upon entry and every time we pass through the "if (index < layerSize)" condition, ctx[mmFriQueue:] holds an array of triplets (query index, FRI value, FRI inversed point), i.e. ctx[mmFriQueue::3] holds query indices. ctx[mmFriQueue + 1::3] holds the input for the next layer. ctx[mmFriQueue + 2::3] holds the inverses of the evaluation points: ctx[mmFriQueue + 3*i + 2] = inverse( fpow(layerGenerator, bitReverse(ctx[mmFriQueue + 3*i], logLayerSize)). */ function friVerifyLayers( uint256[] memory ctx) internal view { uint256 friCtx = getPtr(ctx, MM_FRI_CTX); require( MAX_SUPPORTED_MAX_FRI_STEP == FRI_MAX_FRI_STEP, "Incosistent MAX_FRI_STEP between MemoryMap.sol and FriLayer.sol"); initFriGroups(friCtx); // emit LogGas("FRI offset precomputation", gasleft()); uint256 channelPtr = getChannelPtr(ctx); uint256 merkleQueuePtr = getMerkleQueuePtr(ctx); uint256 friStep = 1; uint256 nLiveQueries = ctx[MM_N_UNIQUE_QUERIES]; // Add 0 at the end of the queries array to avoid empty array check in readNextElment. ctx[MM_FRI_QUERIES_DELIMITER] = 0; // Rather than converting all the values from Montgomery to standard form, // we can just pretend that the values are in standard form but all // the committed polynomials are multiplied by MontgomeryR. // // The values in the proof are already multiplied by MontgomeryR, // but the inputs from the OODS oracle need to be fixed. for (uint256 i = 0; i < nLiveQueries; i++ ) { ctx[MM_FRI_QUEUE + 3*i + 1] = fmul(ctx[MM_FRI_QUEUE + 3*i + 1], K_MONTGOMERY_R); } uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256[] memory friSteps = getFriSteps(ctx); uint256 nFriSteps = friSteps.length; while (friStep < nFriSteps) { uint256 friCosetSize = 2**friSteps[friStep]; nLiveQueries = computeNextLayer( channelPtr, friQueue, merkleQueuePtr, nLiveQueries, ctx[MM_FRI_EVAL_POINTS + friStep], friCosetSize, friCtx); // emit LogGas( // string(abi.encodePacked("FRI layer ", bytes1(uint8(48 + friStep)))), gasleft()); // Layer is done, verify the current layer and move to next layer. // ctx[mmMerkleQueue: merkleQueueIdx) holds the indices // and values of the merkle leaves that need verification. verify( channelPtr, merkleQueuePtr, bytes32(ctx[MM_FRI_COMMITMENTS + friStep - 1]), nLiveQueries); // emit LogGas( // string(abi.encodePacked("Merkle of FRI layer ", bytes1(uint8(48 + friStep)))), // gasleft()); friStep++; } verifyLastLayer(ctx, nLiveQueries); // emit LogGas("last FRI layer", gasleft()); } } contract FriStatementVerifier is MemoryMap, MemoryAccessUtils, VerifierChannel, HornerEvaluator { event LogGas(string name, uint256 val); FriStatementContract friStatementContract; constructor(address friStatementContractAddress) internal { friStatementContract = FriStatementContract(friStatementContractAddress); } /* Fast-forwards the queries and invPoints of the friQueue from before the first layer to after the last layer, computes the last FRI layer using horner evalations, then returns the hash of the final FriQueue. */ function computerLastLayerHash(uint256[] memory ctx, uint256 nPoints, uint256 numLayers) internal view returns (bytes32 lastLayerHash) { uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 groupOrderMinusOne = friLastLayerDegBound * ctx[MM_BLOW_UP_FACTOR] - 1; uint256 exponent = 1 << numLayers; uint256 curPointIndex = 0; uint256 prevQuery = 0; uint256 coefsStart = ctx[MM_FRI_LAST_LAYER_PTR]; for (uint256 i = 0; i < nPoints; i++) { uint256 query = ctx[MM_FRI_QUEUE + 3*i] >> numLayers; if (query == prevQuery) { continue; } ctx[MM_FRI_QUEUE + 3*curPointIndex] = query; prevQuery = query; uint256 point = fpow(ctx[MM_FRI_QUEUE + 3*i + 2], exponent); ctx[MM_FRI_QUEUE + 3*curPointIndex + 2] = point; // Invert point using inverse(point) == fpow(point, ord(point) - 1). point = fpow(point, groupOrderMinusOne); ctx[MM_FRI_QUEUE + 3*curPointIndex + 1] = hornerEval( coefsStart, point, friLastLayerDegBound); curPointIndex++; } uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); assembly { lastLayerHash := keccak256(friQueue, mul(curPointIndex, 0x60)) } } /* Verifies that FRI layers consistent with the computed first and last FRI layers have been registered in the FriStatementContract. */ function friVerifyLayers( uint256[] memory ctx) internal view { uint256 channelPtr = getChannelPtr(ctx); uint256 nQueries = ctx[MM_N_UNIQUE_QUERIES]; // Rather than converting all the values from Montgomery to standard form, // we can just pretend that the values are in standard form but all // the committed polynomials are multiplied by MontgomeryR. // // The values in the proof are already multiplied by MontgomeryR, // but the inputs from the OODS oracle need to be fixed. for (uint256 i = 0; i < nQueries; i++ ) { ctx[MM_FRI_QUEUE + 3*i + 1] = fmul(ctx[MM_FRI_QUEUE + 3*i + 1], K_MONTGOMERY_R); } uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 inputLayerHash; assembly { inputLayerHash := keccak256(friQueue, mul(nQueries, 0x60)) } uint256[] memory friSteps = getFriSteps(ctx); uint256 nFriStepsLessOne = friSteps.length - 1; uint256 friStep = 1; uint256 sumSteps = friSteps[1]; uint256[5] memory dataToHash; while (friStep < nFriStepsLessOne) { uint256 outputLayerHash = uint256(readBytes(channelPtr, true)); dataToHash[0] = ctx[MM_FRI_EVAL_POINTS + friStep]; dataToHash[1] = friSteps[friStep]; dataToHash[2] = inputLayerHash; dataToHash[3] = outputLayerHash; dataToHash[4] = ctx[MM_FRI_COMMITMENTS + friStep - 1]; // Verify statement is registered. require( // NOLINT: calls-loop. friStatementContract.isValid(keccak256(abi.encodePacked(dataToHash))), "INVALIDATED_FRI_STATEMENT"); inputLayerHash = outputLayerHash; friStep++; sumSteps += friSteps[friStep]; } dataToHash[0] = ctx[MM_FRI_EVAL_POINTS + friStep]; dataToHash[1] = friSteps[friStep]; dataToHash[2] = inputLayerHash; dataToHash[3] = uint256(computerLastLayerHash(ctx, nQueries, sumSteps)); dataToHash[4] = ctx[MM_FRI_COMMITMENTS + friStep - 1]; require( friStatementContract.isValid(keccak256(abi.encodePacked(dataToHash))), "INVALIDATED_FRI_STATEMENT"); } } contract StarkVerifier is MemoryMap, MemoryAccessUtils, VerifierChannel, IStarkVerifier, Fri { /* The work required to generate an invalid proof is 2^numSecurityBits. Typical values: 80-128. */ uint256 numSecurityBits; /* The secuirty of a proof is a composition of bits obtained by PoW and bits obtained by FRI queries. The verifier requires at least minProofOfWorkBits to be obtained by PoW. Typical values: 20-30. */ uint256 minProofOfWorkBits; constructor(uint256 numSecurityBits_, uint256 minProofOfWorkBits_) public { numSecurityBits = numSecurityBits_; minProofOfWorkBits = minProofOfWorkBits_; } /* To print LogDebug messages from assembly use code like the following: assembly { let val := 0x1234 mstore(0, val) // uint256 val // log to the LogDebug(uint256) topic log1(0, 0x20, 0x2feb477e5c8c82cfb95c787ed434e820b1a28fa84d68bbf5aba5367382f5581c) } Note that you can't use log in a contract that was called with staticcall (ContraintPoly, Oods,...) If logging is needed replace the staticcall to call and add a third argument of 0. */ event LogBool(bool val); event LogDebug(uint256 val); address oodsContractAddress; function airSpecificInit(uint256[] memory publicInput) internal view returns (uint256[] memory ctx, uint256 logTraceLength); uint256 constant internal PROOF_PARAMS_N_QUERIES_OFFSET = 0; uint256 constant internal PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET = 1; uint256 constant internal PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET = 2; uint256 constant internal PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET = 3; uint256 constant internal PROOF_PARAMS_N_FRI_STEPS_OFFSET = 4; uint256 constant internal PROOF_PARAMS_FRI_STEPS_OFFSET = 5; function validateFriParams( uint256[] memory friSteps, uint256 logTraceLength, uint256 logFriLastLayerDegBound) internal pure { require (friSteps[0] == 0, "Only eta0 == 0 is currently supported"); uint256 expectedLogDegBound = logFriLastLayerDegBound; uint256 nFriSteps = friSteps.length; for (uint256 i = 1; i < nFriSteps; i++) { uint256 friStep = friSteps[i]; require(friStep > 0, "Only the first fri step can be 0"); require(friStep <= 4, "Max supported fri step is 4."); expectedLogDegBound += friStep; } // FRI starts with a polynomial of degree 'traceLength'. // After applying all the FRI steps we expect to get a polynomial of degree less // than friLastLayerDegBound. require ( expectedLogDegBound == logTraceLength, "Fri params do not match trace length"); } function initVerifierParams(uint256[] memory publicInput, uint256[] memory proofParams) internal view returns (uint256[] memory ctx) { require (proofParams.length > PROOF_PARAMS_FRI_STEPS_OFFSET, "Invalid proofParams."); require ( proofParams.length == ( PROOF_PARAMS_FRI_STEPS_OFFSET + proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]), "Invalid proofParams."); uint256 logBlowupFactor = proofParams[PROOF_PARAMS_LOG_BLOWUP_FACTOR_OFFSET]; require (logBlowupFactor <= 16, "logBlowupFactor must be at most 16"); require (logBlowupFactor >= 1, "logBlowupFactor must be at least 1"); uint256 proofOfWorkBits = proofParams[PROOF_PARAMS_PROOF_OF_WORK_BITS_OFFSET]; require (proofOfWorkBits <= 50, "proofOfWorkBits must be at most 50"); require (proofOfWorkBits >= minProofOfWorkBits, "minimum proofOfWorkBits not satisfied"); require (proofOfWorkBits < numSecurityBits, "Proofs may not be purely based on PoW."); uint256 logFriLastLayerDegBound = ( proofParams[PROOF_PARAMS_FRI_LAST_LAYER_DEG_BOUND_OFFSET] ); require ( logFriLastLayerDegBound <= 10, "logFriLastLayerDegBound must be at most 10."); uint256 nFriSteps = proofParams[PROOF_PARAMS_N_FRI_STEPS_OFFSET]; require (nFriSteps <= 10, "Too many fri steps."); require (nFriSteps > 1, "Not enough fri steps."); uint256[] memory friSteps = new uint256[](nFriSteps); for (uint256 i = 0; i < nFriSteps; i++) { friSteps[i] = proofParams[PROOF_PARAMS_FRI_STEPS_OFFSET + i]; } uint256 logTraceLength; (ctx, logTraceLength) = airSpecificInit(publicInput); validateFriParams(friSteps, logTraceLength, logFriLastLayerDegBound); uint256 friStepsPtr = getPtr(ctx, MM_FRI_STEPS_PTR); assembly { mstore(friStepsPtr, friSteps) } ctx[MM_FRI_LAST_LAYER_DEG_BOUND] = 2**logFriLastLayerDegBound; ctx[MM_TRACE_LENGTH] = 2 ** logTraceLength; ctx[MM_BLOW_UP_FACTOR] = 2**logBlowupFactor; ctx[MM_PROOF_OF_WORK_BITS] = proofOfWorkBits; uint256 nQueries = proofParams[PROOF_PARAMS_N_QUERIES_OFFSET]; require (nQueries > 0, "Number of queries must be at least one"); require (nQueries <= MAX_N_QUERIES, "Too many queries."); require ( nQueries * logBlowupFactor + proofOfWorkBits >= numSecurityBits, "Proof params do not satisfy security requirements."); ctx[MM_N_UNIQUE_QUERIES] = nQueries; // We start with log_evalDomainSize = logTraceSize and update it here. ctx[MM_LOG_EVAL_DOMAIN_SIZE] = logTraceLength + logBlowupFactor; ctx[MM_EVAL_DOMAIN_SIZE] = 2**ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 gen_evalDomain = fpow(GENERATOR_VAL, (K_MODULUS - 1) / ctx[MM_EVAL_DOMAIN_SIZE]); ctx[MM_EVAL_DOMAIN_GENERATOR] = gen_evalDomain; uint256 genTraceDomain = fpow(gen_evalDomain, ctx[MM_BLOW_UP_FACTOR]); ctx[MM_TRACE_GENERATOR] = genTraceDomain; } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32); function oodsConsistencyCheck(uint256[] memory ctx) internal view; function getNColumnsInTrace() internal pure returns(uint256); function getNColumnsInComposition() internal pure returns(uint256); function getMmCoefficients() internal pure returns(uint256); function getMmOodsValues() internal pure returns(uint256); function getMmOodsCoefficients() internal pure returns(uint256); function getNCoefficients() internal pure returns(uint256); function getNOodsValues() internal pure returns(uint256); function getNOodsCoefficients() internal pure returns(uint256); // Interaction functions. // If the AIR uses interaction, the following functions should be overridden. function getNColumnsInTrace0() internal pure returns(uint256) { return getNColumnsInTrace(); } function getNColumnsInTrace1() internal pure returns(uint256) { return 0; } function getMmInteractionElements() internal pure returns(uint256) { require(false, "AIR does not support interaction."); } function getNInteractionElements() internal pure returns(uint256) { require(false, "AIR does not support interaction."); } function hasInteraction() internal pure returns (bool) { return getNColumnsInTrace1() > 0; } function hashRow(uint256[] memory ctx, uint256 offset, uint256 length) internal pure returns (uint256 res) { assembly { res := keccak256(add(add(ctx, 0x20), offset), length) } res &= getHashMask(); } /* Adjusts the query indices and generates evaluation points for each query index. The operations above are independent but we can save gas by combining them as both operations require us to iterate the queries array. Indices adjustment: The query indices adjustment is needed because both the Merkle verification and FRI expect queries "full binary tree in array" indices. The adjustment is simply adding evalDomainSize to each query. Note that evalDomainSize == 2^(#FRI layers) == 2^(Merkle tree hight). evalPoints generation: for each query index "idx" we compute the corresponding evaluation point: g^(bitReverse(idx, log_evalDomainSize). */ function adjustQueryIndicesAndPrepareEvalPoints(uint256[] memory ctx) internal view { uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 evalPointsPtr = getPtr(ctx, MM_OODS_EVAL_POINTS); uint256 log_evalDomainSize = ctx[MM_LOG_EVAL_DOMAIN_SIZE]; uint256 evalDomainSize = ctx[MM_EVAL_DOMAIN_SIZE]; uint256 evalDomainGenerator = ctx[MM_EVAL_DOMAIN_GENERATOR]; assembly { /* Returns the bit reversal of value assuming it has the given number of bits. numberOfBits must be <= 64. */ function bitReverse(value, numberOfBits) -> res { // Bit reverse value by swapping 1 bit chunks then 2 bit chunks and so forth. // Each swap is done by masking out and shifting one of the chunks by twice its size. // Finally, we use div to align the result to the right. res := value // Swap 1 bit chunks. res := or(mul(and(res, 0x5555555555555555), 0x4), and(res, 0xaaaaaaaaaaaaaaaa)) // Swap 2 bit chunks. res := or(mul(and(res, 0x6666666666666666), 0x10), and(res, 0x19999999999999998)) // Swap 4 bit chunks. res := or(mul(and(res, 0x7878787878787878), 0x100), and(res, 0x78787878787878780)) // Swap 8 bit chunks. res := or(mul(and(res, 0x7f807f807f807f80), 0x10000), and(res, 0x7f807f807f807f8000)) // Swap 16 bit chunks. res := or(mul(and(res, 0x7fff80007fff8000), 0x100000000), and(res, 0x7fff80007fff80000000)) // Swap 32 bit chunks. res := or(mul(and(res, 0x7fffffff80000000), 0x10000000000000000), and(res, 0x7fffffff8000000000000000)) // Right align the result. res := div(res, exp(2, sub(127, numberOfBits))) } function expmod(base, exponent, modulus) -> res { let p := mload(0x40) mstore(p, 0x20) // Length of Base. mstore(add(p, 0x20), 0x20) // Length of Exponent. mstore(add(p, 0x40), 0x20) // Length of Modulus. mstore(add(p, 0x60), base) // Base. mstore(add(p, 0x80), exponent) // Exponent. mstore(add(p, 0xa0), modulus) // Modulus. // Call modexp precompile. if iszero(staticcall(gas, 0x05, p, 0xc0, p, 0x20)) { revert(0, 0) } res := mload(p) } let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001 for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let queryIdx := mload(friQueue) // Adjust queryIdx, see comment in function description. let adjustedQueryIdx := add(queryIdx, evalDomainSize) mstore(friQueue, adjustedQueryIdx) // Compute the evaluation point corresponding to the current queryIdx. mstore(evalPointsPtr, expmod(evalDomainGenerator, bitReverse(queryIdx, log_evalDomainSize), PRIME)) evalPointsPtr := add(evalPointsPtr, 0x20) } } } /* Reads query responses for nColumns from the channel with the corresponding authentication paths. Verifies the consistency of the authentication paths with respect to the given merkleRoot, and stores the query values in proofDataPtr. nTotalColumns is the total number of columns represented in proofDataPtr (which should be an array of nUniqueQueries rows of size nTotalColumns). nColumns is the number of columns for which data will be read by this function. The change to the proofDataPtr array will be as follows: * The first nColumns cells will be set, * The next nTotalColumns - nColumns will be skipped, * The next nColumns cells will be set, * The next nTotalColumns - nColumns will be skipped, * ... To set the last columns for each query simply add an offset to proofDataPtr before calling the function. */ function readQueryResponsesAndDecommit( uint256[] memory ctx, uint256 nTotalColumns, uint256 nColumns, uint256 proofDataPtr, bytes32 merkleRoot) internal view { require(nColumns <= getNColumnsInTrace() + getNColumnsInComposition(), "Too many columns."); uint256 nUniqueQueries = ctx[MM_N_UNIQUE_QUERIES]; uint256 channelPtr = getPtr(ctx, MM_CHANNEL); uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 friQueueEnd = friQueue + nUniqueQueries * 0x60; uint256 merkleQueuePtr = getPtr(ctx, MM_MERKLE_QUEUE); uint256 rowSize = 0x20 * nColumns; uint256 lhashMask = getHashMask(); uint256 proofDataSkipBytes = 0x20 * (nTotalColumns - nColumns); assembly { let proofPtr := mload(channelPtr) let merklePtr := merkleQueuePtr for {} lt(friQueue, friQueueEnd) {friQueue := add(friQueue, 0x60)} { let merkleLeaf := and(keccak256(proofPtr, rowSize), lhashMask) if eq(rowSize, 0x20) { // If a leaf contains only 1 field element we don't hash it. merkleLeaf := mload(proofPtr) } // push(queryIdx, hash(row)) to merkleQueue. mstore(merklePtr, mload(friQueue)) mstore(add(merklePtr, 0x20), merkleLeaf) merklePtr := add(merklePtr, 0x40) // Copy query responses to proofData array. // This array will be sent to the OODS contract. for {let proofDataChunk_end := add(proofPtr, rowSize)} lt(proofPtr, proofDataChunk_end) {proofPtr := add(proofPtr, 0x20)} { mstore(proofDataPtr, mload(proofPtr)) proofDataPtr := add(proofDataPtr, 0x20) } proofDataPtr := add(proofDataPtr, proofDataSkipBytes) } mstore(channelPtr, proofPtr) } verify(channelPtr, merkleQueuePtr, merkleRoot, nUniqueQueries); } /* Computes the first FRI layer by reading the query responses and calling the OODS contract. The OODS contract will build and sum boundary constraints that check that the prover provided the proper evaluations for the Out of Domain Sampling. I.e. if the prover said that f(z) = c, the first FRI layer will include the term (f(x) - c)/(x-z). */ function computeFirstFriLayer(uint256[] memory ctx) internal view { adjustQueryIndicesAndPrepareEvalPoints(ctx); // emit LogGas("Prepare evaluation points", gasleft()); readQueryResponsesAndDecommit( ctx, getNColumnsInTrace(), getNColumnsInTrace0(), getPtr(ctx, MM_TRACE_QUERY_RESPONSES), bytes32(ctx[MM_TRACE_COMMITMENT])); // emit LogGas("Read and decommit trace", gasleft()); if (hasInteraction()) { readQueryResponsesAndDecommit( ctx, getNColumnsInTrace(), getNColumnsInTrace1(), getPtr(ctx, MM_TRACE_QUERY_RESPONSES + getNColumnsInTrace0()), bytes32(ctx[MM_TRACE_COMMITMENT + 1])); // emit LogGas("Read and decommit second trace", gasleft()); } readQueryResponsesAndDecommit( ctx, getNColumnsInComposition(), getNColumnsInComposition(), getPtr(ctx, MM_COMPOSITION_QUERY_RESPONSES), bytes32(ctx[MM_OODS_COMMITMENT])); // emit LogGas("Read and decommit composition", gasleft()); address oodsAddress = oodsContractAddress; uint256 friQueue = getPtr(ctx, MM_FRI_QUEUE); uint256 returnDataSize = MAX_N_QUERIES * 0x60; assembly { // Call the OODS contract. if iszero(staticcall(not(0), oodsAddress, ctx, /*sizeof(ctx)*/ mul(add(mload(ctx), 1), 0x20), friQueue, returnDataSize)) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // emit LogGas("OODS virtual oracle", gasleft()); } /* Reads the last FRI layer (i.e. the polynomial's coefficients) from the channel. This differs from standard reading of channel field elements in several ways: -- The digest is updated by hashing it once with all coefficients simultaneously, rather than iteratively one by one. -- The coefficients are kept in Montgomery form, as is the case throughout the FRI computation. -- The coefficients are not actually read and copied elsewhere, but rather only a pointer to their location in the channel is stored. */ function readLastFriLayer(uint256[] memory ctx) internal pure { uint256 lmmChannel = MM_CHANNEL; uint256 friLastLayerDegBound = ctx[MM_FRI_LAST_LAYER_DEG_BOUND]; uint256 lastLayerPtr; uint256 badInput = 0; assembly { let primeMinusOne := 0x800000000000011000000000000000000000000000000000000000000000000 let channelPtr := add(add(ctx, 0x20), mul(lmmChannel, 0x20)) lastLayerPtr := mload(channelPtr) // Make sure all the values are valid field elements. let length := mul(friLastLayerDegBound, 0x20) let lastLayerEnd := add(lastLayerPtr, length) for { let coefsPtr := lastLayerPtr } lt(coefsPtr, lastLayerEnd) { coefsPtr := add(coefsPtr, 0x20) } { badInput := or(badInput, gt(mload(coefsPtr), primeMinusOne)) } // Copy the digest to the proof area // (store it before the coefficients - this is done because // keccak256 needs all data to be consecutive), // then hash and place back in digestPtr. let newDigestPtr := sub(lastLayerPtr, 0x20) let digestPtr := add(channelPtr, 0x20) // Overwriting the proof to minimize copying of data. mstore(newDigestPtr, mload(digestPtr)) // prng.digest := keccak256(digest||lastLayerCoefs). mstore(digestPtr, keccak256(newDigestPtr, add(length, 0x20))) // prng.counter := 0. mstore(add(channelPtr, 0x40), 0) // Note: proof pointer is not incremented until this point. mstore(channelPtr, lastLayerEnd) } require(badInput == 0, "Invalid field element."); ctx[MM_FRI_LAST_LAYER_PTR] = lastLayerPtr; } function verifyProof( uint256[] memory proofParams, uint256[] memory proof, uint256[] memory publicInput) internal view { // emit LogGas("Transmission", gasleft()); uint256[] memory ctx = initVerifierParams(publicInput, proofParams); uint256 channelPtr = getChannelPtr(ctx); initChannel(channelPtr, getProofPtr(proof), getPublicInputHash(publicInput)); // emit LogGas("Initializations", gasleft()); // Read trace commitment. ctx[MM_TRACE_COMMITMENT] = uint256(readHash(channelPtr, true)); if (hasInteraction()) { // Send interaction elements. VerifierChannel.sendFieldElements( channelPtr, getNInteractionElements(), getPtr(ctx, getMmInteractionElements())); // Read second trace commitment. ctx[MM_TRACE_COMMITMENT + 1] = uint256(readHash(channelPtr, true)); } VerifierChannel.sendFieldElements( channelPtr, getNCoefficients(), getPtr(ctx, getMmCoefficients())); // emit LogGas("Generate coefficients", gasleft()); ctx[MM_OODS_COMMITMENT] = uint256(readHash(channelPtr, true)); // Send Out of Domain Sampling point. VerifierChannel.sendFieldElements(channelPtr, 1, getPtr(ctx, MM_OODS_POINT)); // Read the answers to the Out of Domain Sampling. uint256 lmmOodsValues = getMmOodsValues(); for (uint256 i = lmmOodsValues; i < lmmOodsValues+getNOodsValues(); i++) { ctx[i] = VerifierChannel.readFieldElement(channelPtr, true); } // emit LogGas("Read OODS commitments", gasleft()); oodsConsistencyCheck(ctx); // emit LogGas("OODS consistency check", gasleft()); VerifierChannel.sendFieldElements( channelPtr, getNOodsCoefficients(), getPtr(ctx, getMmOodsCoefficients())); // emit LogGas("Generate OODS coefficients", gasleft()); ctx[MM_FRI_COMMITMENTS] = uint256(VerifierChannel.readHash(channelPtr, true)); uint256 nFriSteps = getFriSteps(ctx).length; uint256 fri_evalPointPtr = getPtr(ctx, MM_FRI_EVAL_POINTS); for (uint256 i = 1; i < nFriSteps - 1; i++) { VerifierChannel.sendFieldElements(channelPtr, 1, fri_evalPointPtr + i * 0x20); ctx[MM_FRI_COMMITMENTS + i] = uint256(VerifierChannel.readHash(channelPtr, true)); } // Send last random FRI evaluation point. VerifierChannel.sendFieldElements( channelPtr, 1, getPtr(ctx, MM_FRI_EVAL_POINTS + nFriSteps - 1)); // Read FRI last layer commitment. readLastFriLayer(ctx); // Generate queries. // emit LogGas("Read FRI commitments", gasleft()); VerifierChannel.verifyProofOfWork(channelPtr, ctx[MM_PROOF_OF_WORK_BITS]); ctx[MM_N_UNIQUE_QUERIES] = VerifierChannel.sendRandomQueries( channelPtr, ctx[MM_N_UNIQUE_QUERIES], ctx[MM_EVAL_DOMAIN_SIZE] - 1, getPtr(ctx, MM_FRI_QUEUE), 0x60); // emit LogGas("Send queries", gasleft()); computeFirstFriLayer(ctx); friVerifyLayers(ctx); } } contract CpuVerifier is StarkParameters, StarkVerifier, CpuPublicInputOffsets, CairoVerifierContract, MemoryPageFactRegistryConstants { CpuConstraintPoly constraintPoly; PeriodicColumnContract pedersenPointsX; PeriodicColumnContract pedersenPointsY; PeriodicColumnContract ecdsaPointsX; PeriodicColumnContract ecdsaPointsY; IFactRegistry memoryPageFactRegistry; constructor( address[] memory auxPolynomials, address oodsContract, address memoryPageFactRegistry_, uint256 numSecurityBits_, uint256 minProofOfWorkBits_) StarkVerifier( numSecurityBits_, minProofOfWorkBits_ ) public { constraintPoly = CpuConstraintPoly(auxPolynomials[0]); pedersenPointsX = PeriodicColumnContract(auxPolynomials[1]); pedersenPointsY = PeriodicColumnContract(auxPolynomials[2]); ecdsaPointsX = PeriodicColumnContract(auxPolynomials[3]); ecdsaPointsY = PeriodicColumnContract(auxPolynomials[4]); oodsContractAddress = oodsContract; memoryPageFactRegistry = IFactRegistry(memoryPageFactRegistry_); } function verifyProofExternal( uint256[] calldata proofParams, uint256[] calldata proof, uint256[] calldata publicInput) external { verifyProof(proofParams, proof, publicInput); } function getNColumnsInTrace() internal pure returns (uint256) { return N_COLUMNS_IN_MASK; } function getNColumnsInTrace0() internal pure returns (uint256) { return N_COLUMNS_IN_TRACE0; } function getNColumnsInTrace1() internal pure returns (uint256) { return N_COLUMNS_IN_TRACE1; } function getNColumnsInComposition() internal pure returns (uint256) { return CONSTRAINTS_DEGREE_BOUND; } function getMmInteractionElements() internal pure returns (uint256) { return MM_INTERACTION_ELEMENTS; } function getMmCoefficients() internal pure returns (uint256) { return MM_COEFFICIENTS; } function getMmOodsValues() internal pure returns (uint256) { return MM_OODS_VALUES; } function getMmOodsCoefficients() internal pure returns (uint256) { return MM_OODS_COEFFICIENTS; } function getNInteractionElements() internal pure returns (uint256) { return N_INTERACTION_ELEMENTS; } function getNCoefficients() internal pure returns (uint256) { return N_COEFFICIENTS; } function getNOodsValues() internal pure returns (uint256) { return N_OODS_VALUES; } function getNOodsCoefficients() internal pure returns (uint256) { return N_OODS_COEFFICIENTS; } function airSpecificInit( uint256[] memory publicInput ) internal view returns (uint256[] memory ctx, uint256 logTraceLength) { require( publicInput.length >= OFFSET_PUBLIC_MEMORY, "publicInput is too short."); ctx = new uint256[](MM_CONTEXT_SIZE); // Context for generated code. ctx[MM_OFFSET_SIZE] = 2**16; ctx[MM_HALF_OFFSET_SIZE] = 2**15; // Number of steps. uint256 logNSteps = publicInput[OFFSET_LOG_N_STEPS]; require(logNSteps < 50, "Number of steps is too large."); ctx[MM_LOG_N_STEPS] = logNSteps; logTraceLength = logNSteps + LOG_CPU_COMPONENT_HEIGHT; // Range check limits. ctx[MM_RC_MIN] = publicInput[OFFSET_RC_MIN]; ctx[MM_RC_MAX] = publicInput[OFFSET_RC_MAX]; require(ctx[MM_RC_MIN] <= ctx[MM_RC_MAX], "rc_min must be <= rc_max"); require(ctx[MM_RC_MAX] < ctx[MM_OFFSET_SIZE], "rc_max out of range"); // Layout. require(publicInput[OFFSET_LAYOUT_CODE] == LAYOUT_CODE, "Layout code mismatch."); // Initial and final pc ("program" memory segment). ctx[MM_INITIAL_PC] = publicInput[OFFSET_PROGRAM_BEGIN_ADDR]; ctx[MM_FINAL_PC] = publicInput[OFFSET_PROGRAM_STOP_PTR]; // Invalid final pc may indicate that the program end was moved, or the program didn't // complete. require(ctx[MM_INITIAL_PC] == 0, "Invalid initial pc"); require(ctx[MM_FINAL_PC] == 2, "Invalid final pc"); // Initial and final ap ("execution" memory segment). ctx[MM_INITIAL_AP] = publicInput[OFFSET_EXECUTION_BEGIN_ADDR]; ctx[MM_FINAL_AP] = publicInput[OFFSET_EXECUTION_STOP_PTR]; { // "output" memory segment. uint256 outputBeginAddr = publicInput[OFFSET_OUTPUT_BEGIN_ADDR]; uint256 outputStopPtr = publicInput[OFFSET_OUTPUT_STOP_PTR]; require(outputBeginAddr <= outputStopPtr, "output begin_addr must be <= stop_ptr"); require(outputStopPtr < 2**64, "Out of range output stop_ptr."); } // "checkpoints" memory segment. ctx[MM_INITIAL_CHECKPOINTS_ADDR] = publicInput[OFFSET_CHECKPOINTS_BEGIN_PTR]; ctx[MM_FINAL_CHECKPOINTS_ADDR] = publicInput[OFFSET_CHECKPOINTS_STOP_PTR]; require( ctx[MM_INITIAL_CHECKPOINTS_ADDR] <= ctx[MM_FINAL_CHECKPOINTS_ADDR], "checkpoints begin_addr must be <= stop_ptr"); require(ctx[MM_FINAL_CHECKPOINTS_ADDR] < 2**64, "Out of range checkpoints stop_ptr."); require( (ctx[MM_FINAL_CHECKPOINTS_ADDR] - ctx[MM_INITIAL_CHECKPOINTS_ADDR]) % 2 == 0, "Checkpoints should occupy an even number of cells."); // "pedersen" memory segment. ctx[MM_INITIAL_PEDERSEN_ADDR] = publicInput[OFFSET_PEDERSEN_BEGIN_ADDR]; require(ctx[MM_INITIAL_PEDERSEN_ADDR] < 2**64, "Out of range pedersen begin_addr."); uint256 pedersenStopPtr = publicInput[OFFSET_PEDERSEN_STOP_PTR]; uint256 pedersenMaxStopPtr = ctx[MM_INITIAL_PEDERSEN_ADDR] + 3 * safeDiv( 2 ** ctx[MM_LOG_N_STEPS], PEDERSEN_BUILTIN_RATIO); require( ctx[MM_INITIAL_PEDERSEN_ADDR] <= pedersenStopPtr && pedersenStopPtr <= pedersenMaxStopPtr, "Invalid pedersen stop_ptr"); // "range_check" memory segment. ctx[MM_INITIAL_RC_ADDR] = publicInput[OFFSET_RANGE_CHECK_BEGIN_ADDR]; require(ctx[MM_INITIAL_RC_ADDR] < 2**64, "Out of range range_check begin_addr."); uint256 rcStopPtr = publicInput[OFFSET_RANGE_CHECK_STOP_PTR]; uint256 rcMaxStopPtr = ctx[MM_INITIAL_RC_ADDR] + safeDiv(2 ** ctx[MM_LOG_N_STEPS], RC_BUILTIN_RATIO); require( ctx[MM_INITIAL_RC_ADDR] <= rcStopPtr && rcStopPtr <= rcMaxStopPtr, "Invalid range_check stop_ptr"); // "ecdsa" memory segment. ctx[MM_INITIAL_ECDSA_ADDR] = publicInput[OFFSET_ECDSA_BEGIN_ADDR]; require(ctx[MM_INITIAL_ECDSA_ADDR] < 2**64, "Out of range ecdsa begin_addr."); uint256 ecdsaStopPtr = publicInput[OFFSET_ECDSA_STOP_PTR]; uint256 ecdsaMaxStopPtr = ctx[MM_INITIAL_ECDSA_ADDR] + 2 * safeDiv(2 ** ctx[MM_LOG_N_STEPS], ECDSA_BUILTIN_RATIO); require( ctx[MM_INITIAL_ECDSA_ADDR] <= ecdsaStopPtr && ecdsaStopPtr <= ecdsaMaxStopPtr, "Invalid ecdsa stop_ptr"); // Public memory. require( publicInput[OFFSET_N_PUBLIC_MEMORY_PAGES] >= 1 && publicInput[OFFSET_N_PUBLIC_MEMORY_PAGES] < 100000, "Invalid number of memory pages."); ctx[MM_N_PUBLIC_MEM_PAGES] = publicInput[OFFSET_N_PUBLIC_MEMORY_PAGES]; { // Compute the total number of public memory entries. uint256 n_public_memory_entries = 0; for (uint256 page = 0; page < ctx[MM_N_PUBLIC_MEM_PAGES]; page++) { uint256 n_page_entries = publicInput[getOffsetPageSize(page)]; require(n_page_entries < 2**30, "Too many public memory entries in one page."); n_public_memory_entries += n_page_entries; } ctx[MM_N_PUBLIC_MEM_ENTRIES] = n_public_memory_entries; } uint256 expectedPublicInputLength = getPublicInputLength(ctx[MM_N_PUBLIC_MEM_PAGES]); require( expectedPublicInputLength == publicInput.length, "Public input length mismatch."); uint256 lmmPublicInputPtr = MM_PUBLIC_INPUT_PTR; assembly { // Set public input pointer to point at the first word of the public input // (skipping length word). mstore(add(ctx, mul(add(lmmPublicInputPtr, 1), 0x20)), add(publicInput, 0x20)) } // Pedersen's shiftPoint values. ctx[MM_PEDERSEN__SHIFT_POINT_X] = 0x49ee3eba8c1600700ee1b87eb599f16716b0b1022947733551fde4050ca6804; ctx[MM_PEDERSEN__SHIFT_POINT_Y] = 0x3ca0cfe4b3bc6ddf346d49d06ea0ed34e621062c0e056c1d0405d266e10268a; ctx[MM_RC16__PERM__PUBLIC_MEMORY_PROD] = 1; ctx[MM_ECDSA__SIG_CONFIG_ALPHA] = 1; ctx[MM_ECDSA__SIG_CONFIG_BETA] = 0x6f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e89; ctx[MM_ECDSA__SIG_CONFIG_SHIFT_POINT_X] = 0x49ee3eba8c1600700ee1b87eb599f16716b0b1022947733551fde4050ca6804; ctx[MM_ECDSA__SIG_CONFIG_SHIFT_POINT_Y] = 0x3ca0cfe4b3bc6ddf346d49d06ea0ed34e621062c0e056c1d0405d266e10268a; } function getPublicInputHash(uint256[] memory publicInput) internal pure returns (bytes32 publicInputHash) { // The initial seed consists of the first part of publicInput. Specifically, it does not // include the page products (which are only known later in the process, as they depend on // the values of z and alpha). uint256 nPages = publicInput[OFFSET_N_PUBLIC_MEMORY_PAGES]; uint256 publicInputSizeForHash = 0x20 * (getOffsetPaddingCell(nPages) + 2); assembly { publicInputHash := keccak256(add(publicInput, 0x20), publicInputSizeForHash) } } function getCoefficients(uint256[] memory ctx) internal pure returns (uint256[N_COEFFICIENTS] memory coefficients) { uint256 offset = 0x20 + MM_COEFFICIENTS * 0x20; assembly { coefficients := add(ctx, offset) } return coefficients; } /* Computes the value of the public memory quotient: numerator / (denominator * padding) where: numerator = (z - (0 + alpha * 0))^S, denominator = \prod_i( z - (addr_i + alpha * value_i) ), padding = (z - (padding_addr + alpha * padding_value))^(S - N), N is the actual number of public memory cells, and S is the number of cells allocated for the public memory (which includes the padding). */ function computePublicMemoryQuotient(uint256[] memory ctx) internal view returns (uint256) { uint256 nValues = ctx[MM_N_PUBLIC_MEM_ENTRIES]; uint256 z = ctx[MM_MEMORY__MULTI_COLUMN_PERM__PERM__INTERACTION_ELM]; uint256 alpha = ctx[MM_MEMORY__MULTI_COLUMN_PERM__HASH_INTERACTION_ELM0]; // The size that is allocated to the public memory. uint256 publicMemorySize = safeDiv(ctx[MM_TRACE_LENGTH], PUBLIC_MEMORY_STEP); require(nValues < 0x1000000, "Overflow protection failed."); require(nValues <= publicMemorySize, "Number of values of public memory is too large."); uint256 nPublicMemoryPages = ctx[MM_N_PUBLIC_MEM_PAGES]; uint256 cumulativeProdsPtr = ctx[MM_PUBLIC_INPUT_PTR] + getOffsetPageProd(0, nPublicMemoryPages) * 0x20; uint256 denominator = computePublicMemoryProd( cumulativeProdsPtr, nPublicMemoryPages, K_MODULUS); // Compute address + alpha * value for the first address-value pair for padding. uint256 publicInputPtr = ctx[MM_PUBLIC_INPUT_PTR]; uint256 paddingOffset = getOffsetPaddingCell(nPublicMemoryPages); uint256 paddingAddr; uint256 paddingValue; assembly { paddingAddr := mload( add(publicInputPtr, mul(0x20, paddingOffset))) paddingValue := mload( add(publicInputPtr, mul(0x20, add(paddingOffset, 1)))) } uint256 hash_first_address_value = fadd(paddingAddr, fmul(paddingValue, alpha)); // Pad the denominator with the shifted value of hash_first_address_value. uint256 denom_pad = fpow( fsub(z, hash_first_address_value), publicMemorySize - nValues); denominator = fmul(denominator, denom_pad); // Calculate the numerator. uint256 numerator = fpow(z, publicMemorySize); // Compute the final result: numerator * denominator^(-1). return fmul(numerator, inverse(denominator)); } /* Computes the cumulative product of the public memory cells: \prod_i( z - (addr_i + alpha * value_i) ). publicMemoryPtr is an array of nValues pairs (address, value). z and alpha are the perm and hash interaction elements required to calculate the product. */ function computePublicMemoryProd( uint256 cumulativeProdsPtr, uint256 nPublicMemoryPages, uint256 prime) internal pure returns (uint256 res) { assembly { let lastPtr := add(cumulativeProdsPtr, mul(nPublicMemoryPages, 0x20)) res := 1 for { let ptr := cumulativeProdsPtr } lt(ptr, lastPtr) { ptr := add(ptr, 0x20) } { res := mulmod(res, mload(ptr), prime) } } } /* Verifies that all the information on each public memory page (size, hash, prod, and possibly address) is consistent with z and alpha, by checking that the corresponding facts were registered on memoryPageFactRegistry. */ function verifyMemoryPageFacts(uint256[] memory ctx) internal view { uint256 nPublicMemoryPages = ctx[MM_N_PUBLIC_MEM_PAGES]; for (uint256 page = 0; page < nPublicMemoryPages; page++) { // Fetch page values from the public input (hash, product and size). uint256 memoryHashPtr = ctx[MM_PUBLIC_INPUT_PTR] + getOffsetPageHash(page) * 0x20; uint256 memoryHash; uint256 prodPtr = ctx[MM_PUBLIC_INPUT_PTR] + getOffsetPageProd(page, nPublicMemoryPages) * 0x20; uint256 prod; uint256 pageSizePtr = ctx[MM_PUBLIC_INPUT_PTR] + getOffsetPageSize(page) * 0x20; uint256 pageSize; assembly { pageSize := mload(pageSizePtr) prod := mload(prodPtr) memoryHash := mload(memoryHashPtr) } uint256 pageAddr = 0; if (page > 0) { uint256 pageAddrPtr = ctx[MM_PUBLIC_INPUT_PTR] + getOffsetPageAddr(page) * 0x20; assembly { pageAddr := mload(pageAddrPtr) } } // Verify that a corresponding fact is registered attesting to the consistency of the page // information with z and alpha. bytes32 factHash = keccak256( abi.encodePacked( page == 0 ? REGULAR_PAGE : CONTINUOUS_PAGE, K_MODULUS, pageSize, /*z=*/ctx[MM_INTERACTION_ELEMENTS], /*alpha=*/ctx[MM_INTERACTION_ELEMENTS + 1], prod, memoryHash, pageAddr) ); require( // NOLINT: calls-loop. memoryPageFactRegistry.isValid(factHash), "Memory page fact was not registered."); } } /* Checks that the trace and the compostion agree at oodsPoint, assuming the prover provided us with the proper evaluations. Later, we will use boundery constraints to check that those evaluations are actully consistent with the commited trace and composition ploynomials. */ function oodsConsistencyCheck(uint256[] memory ctx) internal view { verifyMemoryPageFacts(ctx); uint256 oodsPoint = ctx[MM_OODS_POINT]; // The number of copies in the pedersen hash periodic columns is // nSteps / PEDERSEN_BUILTIN_RATIO / PEDERSEN_BUILTIN_REPETITIONS. uint256 nPedersenHashCopies = safeDiv( 2 ** ctx[MM_LOG_N_STEPS], PEDERSEN_BUILTIN_RATIO * PEDERSEN_BUILTIN_REPETITIONS); uint256 zPointPowPedersen = fpow(oodsPoint, nPedersenHashCopies); ctx[MM_PERIODIC_COLUMN__PEDERSEN__POINTS__X] = pedersenPointsX.compute(zPointPowPedersen); ctx[MM_PERIODIC_COLUMN__PEDERSEN__POINTS__Y] = pedersenPointsY.compute(zPointPowPedersen); // The number of copies in the ECDSA signature periodic columns is // nSteps / ECDSA_BUILTIN_RATIO / ECDSA_BUILTIN_REPETITIONS. uint256 nEcdsaSignatureCopies = safeDiv( 2 ** ctx[MM_LOG_N_STEPS], ECDSA_BUILTIN_RATIO * ECDSA_BUILTIN_REPETITIONS); uint256 zPointPowEcdsa = fpow(oodsPoint, nEcdsaSignatureCopies); ctx[MM_PERIODIC_COLUMN__ECDSA__GENERATOR_POINTS__X] = ecdsaPointsX.compute(zPointPowEcdsa); ctx[MM_PERIODIC_COLUMN__ECDSA__GENERATOR_POINTS__Y] = ecdsaPointsY.compute(zPointPowEcdsa); ctx[MM_MEMORY__MULTI_COLUMN_PERM__PERM__INTERACTION_ELM] = ctx[MM_INTERACTION_ELEMENTS]; ctx[MM_MEMORY__MULTI_COLUMN_PERM__HASH_INTERACTION_ELM0] = ctx[MM_INTERACTION_ELEMENTS + 1]; ctx[MM_RC16__PERM__INTERACTION_ELM] = ctx[MM_INTERACTION_ELEMENTS + 2]; uint256 public_memory_prod = computePublicMemoryQuotient(ctx); ctx[MM_MEMORY__MULTI_COLUMN_PERM__PERM__PUBLIC_MEMORY_PROD] = public_memory_prod; uint256 compositionFromTraceValue; address lconstraintPoly = address(constraintPoly); uint256 offset = 0x20 * (1 + MM_CONSTRAINT_POLY_ARGS_START); uint256 size = 0x20 * (MM_CONSTRAINT_POLY_ARGS_END - MM_CONSTRAINT_POLY_ARGS_START); assembly { // Call CpuConstraintPoly contract. let p := mload(0x40) if iszero( staticcall( not(0), lconstraintPoly, add(ctx, offset), size, p, 0x20 ) ) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } compositionFromTraceValue := mload(p) } uint256 claimedComposition = fadd( ctx[MM_OODS_VALUES + MASK_SIZE], fmul(oodsPoint, ctx[MM_OODS_VALUES + MASK_SIZE + 1]) ); require( compositionFromTraceValue == claimedComposition, "claimedComposition does not match trace" ); } function safeDiv(uint256 numerator, uint256 denominator) internal pure returns (uint256) { require(denominator > 0, "The denominator must not be zero"); require(numerator % denominator == 0, "The numerator is not divisible by the denominator."); return numerator / denominator; } } contract CpuFrilessVerifier is CpuVerifier, MerkleStatementVerifier, FriStatementVerifier { constructor( address[] memory auxPolynomials, address oodsContract, address memoryPageFactRegistry_, address merkleStatementContractAddress, address friStatementContractAddress, uint256 numSecurityBits_, uint256 minProofOfWorkBits_ ) public MerkleStatementVerifier(merkleStatementContractAddress) FriStatementVerifier(friStatementContractAddress) CpuVerifier( auxPolynomials, oodsContract, memoryPageFactRegistry_, numSecurityBits_, minProofOfWorkBits_ ) { // solium-disable-previous-line no-empty-blocks } }
0x608060405234801561001057600080fd5b506004361061002b5760003560e01c80631cb7dd7914610030575b600080fd5b6101446004803603606081101561004657600080fd5b81019060208101813564010000000081111561006157600080fd5b82018360208201111561007357600080fd5b8035906020019184602083028401116401000000008311171561009557600080fd5b9193909290916020810190356401000000008111156100b357600080fd5b8201836020820111156100c557600080fd5b803590602001918460208302840111640100000000831117156100e757600080fd5b91939092909160208101903564010000000081111561010557600080fd5b82018360208201111561011757600080fd5b8035906020019184602083028401116401000000008311171561013957600080fd5b509092509050610146565b005b6101e486868080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525050604080516020808a02828101820190935289825290935089925088918291850190849080828437600092019190915250506040805160208089028281018201909352888252909350889250879182918501908490808284376000920191909152506101ec92505050565b505050505050565b60606101f882856104a5565b9050600061020582610c6d565b90506102228161021486610c74565b61021d86610c77565b610cb3565b61022d816001610cd0565b60001c8260068151811061023d57fe5b602002602001018181525050610251610ce5565b1561029f5761027881610262610cf6565b6102738561026e610cfb565b610d01565b610d83565b610283816001610cd0565b82518390600790811061029257fe5b6020026020010181815250505b6102b7816102ab610ea7565b6102738561026e610ead565b6102c2816001610cd0565b60001c826008815181106102d257fe5b6020026020010181815250506102f08160016102738561015b610d01565b60006102fa610eb3565b9050805b610306610eb9565b82018110156103395761031a836001610ebe565b84828151811061032657fe5b60209081029190910101526001016102fe565b5061034383610ed3565b61035b8261034f610eb9565b6102738661026e61141e565b610366826001610cd0565b60001c836101318151811061037757fe5b602002602001018181525050600061038e84611424565b519050600061039f85610127610d01565b905060015b600183038110156103f1576103c0856001836020028501610d83565b6103cb856001610cd0565b60001c868261013101815181106103de57fe5b60209081029190910101526001016103a4565b50610406846001610273886101268701610d01565b61040f8561143c565b61042d848660038151811061042057fe5b6020026020010151611584565b610470848660098151811061043e57fe5b602002602001015160018860008151811061045557fe5b60200260200101510361046989606d610d01565b6060611676565b8560098151811061047d57fe5b60200260200101818152505061049285611745565b61049b85611869565b5050505050505050565b6060600582511161051757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f496e76616c69642070726f6f66506172616d732e000000000000000000000000604482015290519081900360640190fd5b8160048151811061052457fe5b602002602001015160050182511461059d57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f496e76616c69642070726f6f66506172616d732e000000000000000000000000604482015290519081900360640190fd5b6000826001815181106105ac57fe5b602002602001015190506010811115610610576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602281526020018061445c6022913960400191505060405180910390fd5b600181101561066a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806143ab6022913960400191505060405180910390fd5b60008360028151811061067957fe5b6020026020010151905060328111156106dd576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806144d46022913960400191505060405180910390fd5b600154811015610738576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806143cd6025913960400191505060405180910390fd5b6000548110610792576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001806141566026913960400191505060405180910390fd5b6000846003815181106107a157fe5b60200260200101519050600a811115610805576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b8152602001806141c5602b913960400191505060405180910390fd5b60008560048151811061081457fe5b60200260200101519050600a81111561088e57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f546f6f206d616e79206672692073746570732e00000000000000000000000000604482015290519081900360640190fd5b600181116108fd57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4e6f7420656e6f756768206672692073746570732e0000000000000000000000604482015290519081900360640190fd5b606081604051908082528060200260200182016040528015610929578160200160208202803883390190505b50905060005b8281101561096d5787816005018151811061094657fe5b602002602001015182828151811061095a57fe5b602090810291909101015260010161092f565b50600061097989611d63565b9097509050610989828286612dfe565b600061099788610126610d01565b90508281528460020a8861013b815181106109ae57fe5b6020026020010181815250508160020a88610141815181106109cc57fe5b6020026020010181815250508660020a886001815181106109e957fe5b6020026020010181815250508588600381518110610a0357fe5b602002602001018181525050600089600081518110610a1e57fe5b6020026020010151905060008111610a81576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260268152602001806142646026913960400191505060405180910390fd5b6030811115610af157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f546f6f206d616e7920717565726965732e000000000000000000000000000000604482015290519081900360640190fd5b60005487898302011015610b50576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603281526020018061432a6032913960400191505060405180910390fd5b8089600981518110610b5e57fe5b60200260200101818152505087830189600281518110610b7a57fe5b60200260200101818152505088600281518110610b9357fe5b602002602001015160020a89600081518110610bab57fe5b6020026020010181815250506000610c0460038b600081518110610bcb57fe5b602002602001015160017f08000000000000110000000000000000000000000000000000000000000000010381610bfe57fe5b04612fde565b9050808a600481518110610c1457fe5b6020026020010181815250506000610c40828c600181518110610c3357fe5b6020026020010151612fde565b9050808b61015a81518110610c5157fe5b6020026020010181815250505050505050505050505092915050565b6101600190565b90565b60008082601281518110610c8757fe5b602002602001015190506000610c9c82613012565b600201602002905080602085012092505050919050565b602082018352610ccb610cc58461301b565b82613021565b505050565b600080610cdd848461302d565b949350505050565b600080610cf0613060565b11905090565b600390565b61015c90565b60008061092c8310610d7457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601a60248201527f4f766572666c6f772070726f74656374696f6e206661696c6564000000000000604482015290519081900360640190fd5b50506020908102919091010190565b63010000008210610df557604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601b60248201527f4f766572666c6f772070726f74656374696f6e206661696c65642e0000000000604482015290519081900360640190fd5b7f08000000000000110000000000000000000000000000000000000000000000017e400000000000011000000000000121000000000000000000000000000000007f0fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff60208601604087016020870286015b80871015610e9c57855b868110610e8a575060408320825160010183528416610e70565b86868209885250602087019650610e66565b505050505050505050565b61012a90565b61015f90565b61028990565b60b090565b600080610cdd610ece858561302d565b613065565b610edc816130b0565b60008161015b81518110610eec57fe5b602002602001015190506000610f1e8361092981518110610f0957fe5b602002602001015160020a6004600802613356565b90506000610f2c8383612fde565b60048054604080517f5ed86d5c0000000000000000000000000000000000000000000000000000000081529283018490525192935073ffffffffffffffffffffffffffffffffffffffff1691635ed86d5c91602480820192602092909190829003018186803b158015610f9e57600080fd5b505afa158015610fb2573d6000803e3d6000fd5b505050506040513d6020811015610fc857600080fd5b50518451859061013d908110610fda57fe5b602090810291909101810191909152600554604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561105557600080fd5b505afa158015611069573d6000803e3d6000fd5b505050506040513d602081101561107f57600080fd5b50518451859061013e90811061109157fe5b60200260200101818152505060006110c685610929815181106110b057fe5b602002602001015160020a600161020002613356565b905060006110d48583612fde565b600654604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101849052905192935073ffffffffffffffffffffffffffffffffffffffff90911691635ed86d5c91602480820192602092909190829003018186803b15801561114957600080fd5b505afa15801561115d573d6000803e3d6000fd5b505050506040513d602081101561117357600080fd5b50518651879061013f90811061118557fe5b602090810291909101810191909152600754604080517f5ed86d5c00000000000000000000000000000000000000000000000000000000815260048101859052905173ffffffffffffffffffffffffffffffffffffffff90921692635ed86d5c92602480840193829003018186803b15801561120057600080fd5b505afa158015611214573d6000803e3d6000fd5b505050506040513d602081101561122a57600080fd5b50518651879061014090811061123c57fe5b6020026020010181815250508561015c8151811061125657fe5b6020026020010151866101488151811061126c57fe5b6020026020010181815250508561015c6001018151811061128957fe5b6020026020010151866101498151811061129f57fe5b6020026020010181815250508561015c600201815181106112bc57fe5b60200260200101518661014b815181106112d257fe5b60200260200101818152505060006112e987613437565b9050808761014a815181106112fa57fe5b60209081029190910181019190915260035460405160009273ffffffffffffffffffffffffffffffffffffffff909216916127c091613f409181838e8601877ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa611369573d6000803e3d6000fd5b805194505060006113b68c60ae610289018151811061138457fe5b60200260200101516113b18d8f60ae61028901600101815181106113a457fe5b602002602001015161368c565b6136b9565b9050808514611410576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602781526020018061419e6027913960400191505060405180910390fd5b505050505050505050505050565b61036990565b6060600061143483610126610d01565b519392505050565b6000600a905060008261013b8151811061145257fe5b60200260200101519050600080600090507f08000000000000110000000000000000000000000000000000000000000000006020850260208701018051935060208502808501855b818110156114b35780518510959095179460200161149a565b50602083810180517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe089019081529390910190922090915260006040830152905250801561156257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f496e76616c6964206669656c6420656c656d656e742e00000000000000000000604482015290519081900360640190fd5b818561013c8151811061157157fe5b6020026020010181815250505050505050565b8061158e57611672565b60007f0123456789abcded00000000000000000000000000000000000000000000000060005260208301518060085282602853602960002060005283518051602052602860002092508160005260286000206020860152600060408601526008810185525050600082610100036001901b905080821061166f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601b60248201527f50726f6f66206f6620776f726b20636865636b206661696c65642e0000000000604482015290519081900360640190fd5b50505b5050565b6000808084815b8881101561172b57826116a35761169b6116968b61301b565b6136e6565b935061010092505b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc09092019183831c88168260005b898211156116f75750878103518083106116ea576116f7565b80825288820391506116d1565b80831461170a5782825293880193611720565b5b8482101561172057818901805190925261170b565b50505060010161167d565b50848682038161173757fe5b049998505050505050505050565b61174e8161371c565b61178b8161175a61391f565b611762613924565b61176e85610419610d01565b8560068151811061177b57fe5b602002602001015160001b613929565b611793610ce5565b156117d1576117d1816117a461391f565b6117ac613060565b6117c1856117b8613924565b61041901610d01565b8560066001018151811061177b57fe5b6117fe816117dd613060565b6117e5613060565b6117f1856108c9610d01565b8560088151811061177b57fe5b60025473ffffffffffffffffffffffffffffffffffffffff16600061182483606d610d01565b8351909150611200908190839060010160200286867ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa61166f573d6000803e3d6000fd5b600061187482610c6d565b905060008260098151811061188557fe5b6020026020010151905060008090505b8181101561190b576118e38482600302606d01600101815181106118b557fe5b60200260200101517f07fffffffffffdf0ffffffffffffffffffffffffffffffffffffffffffffffe161368c565b8482600302606d01600101815181106118f857fe5b6020908102919091010152600101611895565b50600061191984606d610d01565b6060838102822091925061192c86611424565b80519091507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81019060019060009084908390811061196757fe5b60200260200101519050611979614137565b83831015611b8557600061198e8a600161302d565b60001c90508a8461012701815181106119a357fe5b6020026020010151826000600581106119b857fe5b602002015285518690859081106119cb57fe5b6020026020010151826001600581106119e057fe5b602002015260408201879052606082018190528a518b906101308601908110611a0557fe5b602002602001015182600460058110611a1a57fe5b60209081029190910191909152600a5460405173ffffffffffffffffffffffffffffffffffffffff90911691636a93856791859101808260a080838360005b83811015611a71578181015183820152602001611a59565b50505050905001915050604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b158015611ac557600080fd5b505afa158015611ad9573d6000803e3d6000fd5b505050506040513d6020811015611aef57600080fd5b5051611b5c57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f494e56414c4944415445445f4652495f53544154454d454e5400000000000000604482015290519081900360640190fd5b8096508380600101945050858481518110611b7357fe5b60200260200101518301925050611979565b89836101270181518110611b9557fe5b602002602001015181600060058110611baa57fe5b60200201528451859084908110611bbd57fe5b602002602001015181600160058110611bd257fe5b602002015260408101869052611be98a8984613a8a565b606082015289518a906101308501908110611c0057fe5b602002602001015181600460058110611c1557fe5b60209081029190910191909152600a5460405173ffffffffffffffffffffffffffffffffffffffff90911691636a93856791849101808260a080838360005b83811015611c6c578181015183820152602001611c54565b50505050905001915050604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b158015611cc057600080fd5b505afa158015611cd4573d6000803e3d6000fd5b505050506040513d6020811015611cea57600080fd5b5051611d5757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f494e56414c4944415445445f4652495f53544154454d454e5400000000000000604482015290519081900360640190fd5b50505050505050505050565b60606000601383511015611dd857604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f7075626c6963496e70757420697320746f6f2073686f72742e00000000000000604482015290519081900360640190fd5b6040805161092c808252620125a0820190925290602082016201258080388339019050509150620100008261014281518110611e1057fe5b6020026020010181815250506180008261014381518110611e2d57fe5b602002602001018181525050600083600081518110611e4857fe5b6020026020010151905060328110611ec157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f4e756d626572206f6620737465707320697320746f6f206c617267652e000000604482015290519081900360640190fd5b808361092981518110611ed057fe5b60200260200101818152505060048101915083600181518110611eef57fe5b60200260200101518361014d81518110611f0557fe5b60200260200101818152505083600281518110611f1e57fe5b60200260200101518361014e81518110611f3457fe5b6020026020010181815250508261014e81518110611f4e57fe5b60200260200101518361014d81518110611f6457fe5b60200260200101511115611fd957604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601860248201527f72635f6d696e206d757374206265203c3d2072635f6d61780000000000000000604482015290519081900360640190fd5b8261014281518110611fe757fe5b60200260200101518361014e81518110611ffd57fe5b60200260200101511061207157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f72635f6d6178206f7574206f662072616e676500000000000000000000000000604482015290519081900360640190fd5b67706564657273656e8460038151811061208757fe5b6020026020010151146120fb57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f4c61796f757420636f6465206d69736d617463682e0000000000000000000000604482015290519081900360640190fd5b8360048151811061210857fe5b6020026020010151836101458151811061211e57fe5b6020026020010181815250508360058151811061213757fe5b6020026020010151836101478151811061214d57fe5b602002602001018181525050826101458151811061216757fe5b60200260200101516000146121dd57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f496e76616c696420696e697469616c2070630000000000000000000000000000604482015290519081900360640190fd5b82610147815181106121eb57fe5b602002602001015160021461226157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f496e76616c69642066696e616c20706300000000000000000000000000000000604482015290519081900360640190fd5b8360068151811061226e57fe5b6020026020010151836101448151811061228457fe5b6020026020010181815250508360078151811061229d57fe5b602002602001015183610146815181106122b357fe5b6020026020010181815250506000846008815181106122ce57fe5b602002602001015190506000856009815181106122e757fe5b602002602001015190508082111561234a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806142146025913960400191505060405180910390fd5b6801000000000000000081106123c157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f4f7574206f662072616e6765206f75747075742073746f705f7074722e000000604482015290519081900360640190fd5b5050836010815181106123d057fe5b602002602001015183610158815181106123e657fe5b602002602001018181525050836011815181106123ff57fe5b6020026020010151836101598151811061241557fe5b602002602001018181525050826101598151811061242f57fe5b6020026020010151836101588151811061244557fe5b602002602001015111156124a4576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602a815260200180614381602a913960400191505060405180910390fd5b6801000000000000000083610159815181106124bc57fe5b60200260200101511061251a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602281526020018061417c6022913960400191505060405180910390fd5b6002836101588151811061252a57fe5b6020026020010151846101598151811061254057fe5b6020026020010151038161255057fe5b06156125a7576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603281526020018061442a6032913960400191505060405180910390fd5b83600a815181106125b457fe5b602002602001015183610151815181106125ca57fe5b6020026020010181815250506801000000000000000083610151815181106125ee57fe5b60200260200101511061264c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602181526020018061428a6021913960400191505060405180910390fd5b600084600b8151811061265b57fe5b60200260200101519050600061268a856109298151811061267857fe5b602002602001015160020a6008613356565b600302856101518151811061269b57fe5b60200260200101510190508185610151815181106126b557fe5b6020026020010151111580156126cb5750808211155b61273657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f496e76616c696420706564657273656e2073746f705f70747200000000000000604482015290519081900360640190fd5b85600c8151811061274357fe5b6020026020010151856101528151811061275957fe5b60200260200101818152505068010000000000000000856101528151811061277d57fe5b6020026020010151106127db576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602481526020018061447e6024913960400191505060405180910390fd5b600086600d815181106127ea57fe5b602002602001015190506000612807876109298151811061267857fe5b876101528151811061281557fe5b602002602001015101905081876101528151811061282f57fe5b6020026020010151111580156128455750808211155b6128b057604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f496e76616c69642072616e67655f636865636b2073746f705f70747200000000604482015290519081900360640190fd5b87600e815181106128bd57fe5b602002602001015187610157815181106128d357fe5b6020026020010181815250506801000000000000000087610157815181106128f757fe5b60200260200101511061296b57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601e60248201527f4f7574206f662072616e676520656364736120626567696e5f616464722e0000604482015290519081900360640190fd5b600088600f8151811061297a57fe5b6020026020010151905060006129aa896109298151811061299757fe5b602002602001015160020a610200613356565b60020289610157815181106129bb57fe5b60200260200101510190508189610157815181106129d557fe5b6020026020010151111580156129eb5750808211155b612a5657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f496e76616c69642065636473612073746f705f70747200000000000000000000604482015290519081900360640190fd5b60018a601281518110612a6557fe5b602002602001015110158015612a915750620186a08a601281518110612a8757fe5b6020026020010151105b612afc57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f496e76616c6964206e756d626572206f66206d656d6f72792070616765732e00604482015290519081900360640190fd5b89601281518110612b0957fe5b60200260200101518961092b81518110612b1f57fe5b60209081029190910101526000805b8a61092b81518110612b3c57fe5b6020026020010151811015612bd45760008c612b5783613c08565b81518110612b6157fe5b6020026020010151905063400000008110612bc7576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602b815260200180614239602b913960400191505060405180910390fd5b9190910190600101612b2e565b50808a61092a81518110612be457fe5b602002602001018181525050506000612c118a61092b81518110612c0457fe5b6020026020010151613c11565b90508a518114612c8257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f5075626c696320696e707574206c656e677468206d69736d617463682e000000604482015290519081900360640190fd5b60208b0160c08b015289516005907f049ee3eba8c1600700ee1b87eb599f16716b0b1022947733551fde4050ca6804908c9061014f908110612cc057fe5b6020026020010181815250507f03ca0cfe4b3bc6ddf346d49d06ea0ed34e621062c0e056c1d0405d266e10268a8b61015081518110612cfb57fe5b60200260200101818152505060018b61014c81518110612d1757fe5b60200260200101818152505060018b61015381518110612d3357fe5b6020026020010181815250507f06f21413efbe40de150e596d72f7a8c5609ad26c15c915c1f4cdfcb99cee9e898b61015681518110612d6e57fe5b6020026020010181815250507f049ee3eba8c1600700ee1b87eb599f16716b0b1022947733551fde4050ca68048b61015481518110612da957fe5b6020026020010181815250507f03ca0cfe4b3bc6ddf346d49d06ea0ed34e621062c0e056c1d0405d266e10268a8b61015581518110612de457fe5b602002602001018181525050505050505050505050915091565b82600081518110612e0b57fe5b6020026020010151600014612e6b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061435c6025913960400191505060405180910390fd5b8251819060015b81811015612f7e576000868281518110612e8857fe5b6020026020010151905060008111612f0157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820181905260248201527f4f6e6c79207468652066697273742066726920737465702063616e2062652030604482015290519081900360640190fd5b6004811115612f7157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f4d617820737570706f7274656420667269207374657020697320342e00000000604482015290519081900360640190fd5b9290920191600101612e72565b50838214612fd7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806142d76024913960400191505060405180910390fd5b5050505050565b600061300b83837f0800000000000011000000000000000000000000000000000000000000000001613c1a565b9392505050565b60030260120190565b60200190565b61167282826000613c55565b81518051602082018452600091908315610cdd576020850160208101828152604082208252600081525050949350505050565b600290565b60007f08000000000000110000000000000000000000000000000000000000000000017e40000000000001100000000000012100000000000000000000000000000000830992915050565b60008161092b815181106130c057fe5b6020026020010151905060008090505b81811015610ccb5760006130e382613c60565b602002846005815181106130f357fe5b602002602001015101905060008061310b8486613c69565b6020028660058151811061311b57fe5b602002602001015101905060008061313286613c08565b6020028860058151811061314257fe5b602090810291909101015101805184518751965093509091506000871561318f57600061316e89613c78565b6020028b60058151811061317e57fe5b602002602001015101905080519150505b6000881561319e5760016131a1565b60005b7f0800000000000011000000000000000000000000000000000000000000000001848d61015c815181106131d157fe5b60200260200101518e61015c600101815181106131ea57fe5b6020026020010151898c886040516020018089815260200188815260200187815260200186815260200185815260200184815260200183815260200182815260200198505050505050505050604051602081830303815290604052805190602001209050600860009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16636a938567826040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b1580156132c157600080fd5b505afa1580156132d5573d6000803e3d6000fd5b505050506040513d60208110156132eb57600080fd5b5051613342576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806141f06024913960400191505060405180910390fd5b5050600190960195506130d0945050505050565b60008082116133c657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820181905260248201527f5468652064656e6f6d696e61746f72206d757374206e6f74206265207a65726f604482015290519081900360640190fd5b8183816133cf57fe5b0615613426576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260328152602001806144f66032913960400191505060405180910390fd5b81838161342f57fe5b049392505050565b6000808261092a8151811061344857fe5b602002602001015190506000836101488151811061346257fe5b602002602001015190506000846101498151811061347c57fe5b6020026020010151905060006134a8866101418151811061349957fe5b60200260200101516008613356565b90506301000000841061351c57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601b60248201527f4f766572666c6f772070726f74656374696f6e206661696c65642e0000000000604482015290519081900360640190fd5b80841115613575576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602f8152602001806142fb602f913960400191505060405180910390fd5b60008661092b8151811061358557fe5b60200260200101519050600061359c600083613c69565b602002886005815181106135ac57fe5b602002602001015101905060006135e482847f0800000000000011000000000000000000000000000000000000000000000001613cde565b90506000896005815181106135f557fe5b60200260200101519050600061360a85613012565b602080820284015160018301909102840151919250906000613630836113b1848d61368c565b905060006136496136418d84613d08565b8e8c03612fde565b9050613655878261368c565b965060006136638d8c612fde565b9050613677816136728a613d57565b61368c565b9e505050505050505050505050505050919050565b60007f08000000000000110000000000000000000000000000000000000000000000018284099392505050565b60007f08000000000000110000000000000000000000000000000000000000000000018284089392505050565b60008060006136f484613daa565b90925090506137038282613db6565b94509092509050613715848383613c55565b5050919050565b60008160098151811061372b57fe5b60200260200101519050600061374283606d610d01565b9050606082028101600061375885610339610d01565b905060008560028151811061376957fe5b6020026020010151905060008660008151811061378257fe5b6020026020010151905060008760048151811061379b57fe5b602002602001015190506138c4565b600081905067aaaaaaaaaaaaaaaa811660046755555555555555558316021790506801999999999999999881166010676666666666666666831602179050680787878787878787808116610100677878787878787878831602179050687f807f807f807f8000811662010000677f807f807f807f80831602179050697fff80007fff800000008116640100000000677fff80007fff80008316021790506b7fffffff8000000000000000811668010000000000000000677fffffff8000000083160217905082607f0360020a8104905092915050565b600060405160208152602080820152602060408201528260608201528360808201528460a082015260208160c08360055afa6138bb57600080fd5b51949350505050565b7f08000000000000110000000000000000000000000000000000000000000000015b85871015610e9c57865183810180895261390a8361390488856137aa565b86613880565b875260208701965050506060870196506138e6565b601990565b601790565b613931613060565b61393961391f565b018311156139a857604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f546f6f206d616e7920636f6c756d6e732e000000000000000000000000000000604482015290519081900360640190fd5b6000856009815181106139b757fe5b6020026020010151905060006139ce87600a610d01565b905060006139dd88606d610d01565b905060608302810160006139f28a600d610d01565b9050602088026000613a02613de9565b865190915060208b8d030290845b86881015613a6b5783858320166020861415613a2a575081515b885182528060208301526040820191508583015b80841015613a595783518e5260209d8e019d90930192613a3e565b50838d019c5050606088019750613a10565b508752613a7a87858b8b613e0d565b5050505050505050505050505050565b6000808461013b81518110613a9b57fe5b602002602001015190506000600186600181518110613ab657fe5b602002602001015183020390506000846001901b90506000809050600080905060008961013c81518110613ae657fe5b6020026020010151905060008090505b89811015613be3576000898c83600302606d0181518110613b1357fe5b6020026020010151901c905083811415613b2d5750613bdb565b808c86600302606d0181518110613b4057fe5b6020026020010181815250508093506000613b778d84600302606d0160020181518110613b6957fe5b602002602001015188612fde565b9050808d87600302606d0160020181518110613b8f57fe5b602002602001018181525050613ba58189612fde565b9050613bb284828b613fc9565b8d87600302606d0160010181518110613bc757fe5b602090810291909101015250506001909301925b600101613af6565b506000613bf18b606d610d01565b6060949094029093209a9950505050505050505050565b60030260130190565b60040260140190565b600060405160208152602080820152602060408201528460608201528360808201528260a082015260208160c08360055afa6138bb57600080fd5b908252602090910152565b60030260140190565b60038102820160140192915050565b60006001821015613cd4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260328152602001806144a26032913960400191505060405180910390fd5b5060030260120190565b6001602083028401845b81811015613cff5783815184099250602001613ce8565b50509392505050565b60007f0800000000000011000000000000000000000000000000000000000000000001827f08000000000000110000000000000000000000000000000000000000000000010384089392505050565b6000613da4827f0800000000000010ffffffffffffffffffffffffffffffffffffffffffffffff7f0800000000000011000000000000000000000000000000000000000000000001613c1a565b92915050565b80516020820151915091565b60408051602080820185905281830184905282518083038401815260609092019092528051910120919260019091019190565b7fffffffffffffffffffffffffffffffffffffffff00000000000000000000000090565b6000806080831115613e8057604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601760248201527f544f4f5f4d414e595f4d45524b4c455f51554552494553000000000000000000604482015290519081900360640190fd5b604051806040850287015b80881015613ea6578751825260209788019790910190613e8b565b508581526020808201604081815284840383019094206009547f6a9385670000000000000000000000000000000000000000000000000000000090925260248401819052935193945073ffffffffffffffffffffffffffffffffffffffff1692636a938567926044808201939291829003018186803b158015613f2857600080fd5b505afa158015613f3c573d6000803e3d6000fd5b505050506040513d6020811015613f5257600080fd5b5051613fbf57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f494e56414c4944415445445f4d45524b4c455f53544154454d454e5400000000604482015290519081900360640190fd5b5091949350505050565b6000807f08000000000000110000000000000000000000000000000000000000000000016008840615614047576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260388152602001806143f26038913960400191505060405180910390fd5b61100084106140a1576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602c8152602001806142ab602c913960400191505060405180910390fd5b6020840286015b86811115614122577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000181868181818181818a0960e0880151010960c0860151010960a08401510109608082015101925081868388858a878c8a0960608801510109604086015101096020840151010981510192506140a8565b5080828161412c57fe5b069695505050505050565b6040518060a00160405280600590602082028038833950919291505056fe50726f6f6673206d6179206e6f7420626520707572656c79206261736564206f6e20506f572e4f7574206f662072616e676520636865636b706f696e74732073746f705f7074722e636c61696d6564436f6d706f736974696f6e20646f6573206e6f74206d617463682074726163656c6f674672694c6173744c61796572446567426f756e64206d757374206265206174206d6f73742031302e4d656d6f72792070616765206661637420776173206e6f7420726567697374657265642e6f757470757420626567696e5f61646472206d757374206265203c3d2073746f705f707472546f6f206d616e79207075626c6963206d656d6f727920656e747269657320696e206f6e6520706167652e4e756d626572206f662071756572696573206d757374206265206174206c65617374206f6e654f7574206f662072616e676520706564657273656e20626567696e5f616464722e4e6f206d6f7265207468616e203430393620636f656666696369656e74732061726520737570706f7274656446726920706172616d7320646f206e6f74206d61746368207472616365206c656e6774684e756d626572206f662076616c756573206f66207075626c6963206d656d6f727920697320746f6f206c617267652e50726f6f6620706172616d7320646f206e6f74207361746973667920736563757269747920726571756972656d656e74732e4f6e6c792065746130203d3d20302069732063757272656e746c7920737570706f72746564636865636b706f696e747320626567696e5f61646472206d757374206265203c3d2073746f705f7074726c6f67426c6f777570466163746f72206d757374206265206174206c6561737420316d696e696d756d2070726f6f664f66576f726b42697473206e6f74207361746973666965644e756d626572206f6620706f6c796e6f6d69616c20636f656666696369656e7473206d75737420626520646976697369626c652062792038436865636b706f696e74732073686f756c64206f636375707920616e206576656e206e756d626572206f662063656c6c732e6c6f67426c6f777570466163746f72206d757374206265206174206d6f73742031364f7574206f662072616e67652072616e67655f636865636b20626567696e5f616464722e41646472657373206f6620706167652030206973206e6f742070617274206f6620746865207075626c696320696e7075742e70726f6f664f66576f726b42697473206d757374206265206174206d6f7374203530546865206e756d657261746f72206973206e6f7420646976697369626c65206279207468652064656e6f6d696e61746f722ea265627a7a72315820b2a76faf16de3531044ed2195e144797156bd2c880063f6640a5e6e62ebf3a0e64736f6c634300050f0032
[ 3, 4 ]
0x56c8d4e40A709B33cCB19970324880F3a640d9fC
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 999900000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); // fetch all needed data // using LTV as tokenLiquidationThreshold (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLiquidationThreshold,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLiquidationThreshold,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLiquidationThreshold); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return totalCollateralETH; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLiquidationThreshold, totalCollateralETH), wmul(tokenLiquidationThreshold, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLiquidationThreshold)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLiquidationThreshold) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice), NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice), NINETY_NINE_PERCENT_WEI); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_wrappers, rates); } } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] < _rates[minIndex]) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x019739e288973F92bDD3c1d87178E206E51fd911; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Faucet { function gulp(address) public virtual; } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public view virtual returns(uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { // address public constant ETH_FLIPPER = 0xd8a04F5412223F513DC55F839574430f5EC15531; // address public constant BAT_FLIPPER = 0xaA745404d55f88C108A28c86abE7b5A1E7817c07; // address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; // address public constant ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; // address public constant BAT_JOIN = 0x3D0B1912B66114d4096F48A8CEe3A56C231772cA; // bytes32 public constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; // bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; // address public constant SAVER_EXCHANGE = 0x606e9758a39d2d7fA7e70BC68E6E7D9b02948962; // function daiBid(uint _bidId, bool _isEth, uint _amount) public { // uint tendAmount = _amount * (10 ** 27); // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // joinDai(_amount); // (, uint lot, , , , , , ) = Flipper(flipper).bids(_bidId); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).tend(_bidId, lot, tendAmount); // } // function collateralBid(uint _bidId, bool _isEth, uint _amount) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // uint bid; // (bid, , , , , , , ) = Flipper(flipper).bids(_bidId); // joinDai(bid / (10**27)); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).dent(_bidId, _amount, bid); // } // function closeBid(uint _bidId, bool _isEth) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // Flipper(flipper).deal(_bidId); // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function closeBidAndExchange( // uint _bidId, // bool _isEth, // uint256[4] memory _data, // address _exchangeAddress, // bytes memory _callData // ) // public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // (uint bidAmount, , , , , , , ) = Flipper(flipper).bids(_bidId); // Flipper(flipper).deal(_bidId); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(address(this), (bidAmount / 10**27)); // address srcToken = _isEth ? KYBER_ETH_ADDRESS : address(Gem(join).gem()); // uint daiAmount = swap( // _data, // srcToken, // DAI_ADDRESS, // _exchangeAddress, // _callData // ); // ERC20(DAI_ADDRESS).transfer(msg.sender, daiAmount); // } // function exitCollateral(bool _isEth) public { // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function exitDai() public { // uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(DAI_JOIN); // Gem(DAI_JOIN).exit(msg.sender, amount); // } // function withdrawToken(address _token) public { // uint balance = ERC20(_token).balanceOf(address(this)); // ERC20(_token).transfer(msg.sender, balance); // } // function withdrawEth() public { // uint balance = address(this).balance; // msg.sender.transfer(balance); // } // function joinDai(uint _amount) internal { // uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // if (_amount > amountInVat) { // uint amountDiff = (_amount - amountInVat) + 1; // ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); // ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); // Join(DAI_JOIN).join(address(this), amountDiff); // } // } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { address payable public constant MCD_CREATE_FLASH_LOAN = 0xb09bCc172050fBd4562da8b229Cf3E45Dc3045A6; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).transferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).transfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract ManagerLike { function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint wad) public { GemLike(gem).transfer(dst, wad); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract LoanShifterTaker is AdminAuth, ProxyPermission { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_loanShift, _exchangeData); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); uint loanAmount = _loanShift.debtAmount; if (_loanShift.wholeDebt) { loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), loanAmount, paramsData); removePermission(loanShifterReceiverAddr); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } 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) { // 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) { 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 price; bool usageAsCollateralEnabled; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]), totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { approvedCallers[msg.sender] = true; aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x9D266997bc73B27d4302E711b55FD78B5278e1De; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); address payable payableProxy = payable(proxy); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payableProxy).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy uint256 collateralAmount = ERC20(aCollateralToken).balanceOf(user); ERC20(aCollateralToken).safeTransferFrom(user, proxy, collateralAmount); // enable as collateral DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateral(address)", collateralToken)); // withdraw deposited eth DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x56AC1EFC17ecDe083889520137B0cfb30d2cF384; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 80000000000; // 80 gwei uint public REPAY_GAS_COST = 2200000; uint public BOOST_GAS_COST = 1700000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { approvedCallers[msg.sender] = true; compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, address(this).balance, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, address(this).balance, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr); } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2 { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_srcAddr, _destAddr, _destAmount); uint256 srcAmount = wmul(_destAmount, srcRate); rate = getSellRate(_destAddr, _srcAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == KYBER_ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2 { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { address srcAddr = ethToWethAddr(_srcAddr); if (srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(srcAddr).safeTransfer(msg.sender, ERC20(srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2 { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { approvedCallers[msg.sender] = true; monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai }); address collAddr = closeCDP(closeData, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); sendLeftover(collAddr, DAI_ADDRESS, tx.origin); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData ) internal returns (address) { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; address user = DSProxy(payable(_closeData.proxy)).owner(); if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, user); } else { dfsFee = getFee(_closeData.daiAmount, user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = address(Join(_closeData.joinAddr).gem()); require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); return tokenAddr; } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address payable public constant MCD_CLOSE_FLASH_LOAN = 0xdFccc9C59c7361307d47c558ffA75840B32DbA29; address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData ) public payable { MCD_CLOSE_FLASH_LOAN.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(MCD_CLOSE_FLASH_LOAN, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { Join(_joinAddr).gem().approve(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } Join(_joinAddr).gem().approve(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); if (maxDebt >= _exchangeData.srcAmount) { boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); if (maxColl >= _exchangeData.srcAmount) { repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); // if (paramData.swapType == 1) { // COLL_SWAP // exchangeData.srcAmount = getBalance(exchangeData.srcAddr); // (, uint amount) = _sell(exchangeData); // sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); // } else if (paramData.swapType == 2) { // DEBT_SWAP // exchangeData.destAmount = (_amount + _fee); // _buy(exchangeData); // } else { // NO_SWAP just send tokens to proxy // sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); // } // // Execute the Open operation (Skip if it's debt swap) // if (paramData.swapType != 2) { // DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // } // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } // Call specific function if it's a debt swap if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]); } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getWholeDebt(uint _cdpId, address _joinAddr) public virtual returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); // draw coll if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) { uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this)); require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0); } else { require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); } // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); uint256 maxCollateral = getMaxCollateral(_data.srcAddr, address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); IAToken(aTokenCollateral).redeem(_data.srcAmount); // swap (, uint256 destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); uint256 maxBorrow = getMaxBorrow(_data.srcAddr, address(this)); _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, VARIABLE_RATE, AAVE_REFERRAL_CODE); _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, uint256 destAmount) = _sell(_data); if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (address payable proxyAddr, bytes memory proxyData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); // Swap (, uint sellAmount) = _sell(exchangeData); // DFS fee getFee(sellAmount, exchangeData.destAddr, proxyAddr); // Send amount to DSProxy sendToProxy(proxyAddr, exchangeData.destAddr); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(compOpenProxy, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (address payable, bytes memory proxyData, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); return (payable(proxy), proxyData, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x6423708d6B84Af237Ab309dF49f6b8Fb751f28FB; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xBD3140131dEd4426694257411d564791Cc36D382; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); if (_exData.srcAmount <= maxColl) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); if (_exData.srcAmount <= maxBorrow) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } }
0x6080604052600436106101395760003560e01c80637753f47b116100ab578063a26f4f711161006f578063a26f4f711461038e578063a7304bf7146103a3578063bfe142a3146103c3578063deca5f88146103d8578063f851a440146103f8578063fd5452ca1461040d576101bc565b80637753f47b1461031a5780637b925ab11461032f578063870e44d9146103445780638b418713146103595780638da5cb5b14610379576101bc565b80633a128322116100fd5780633a1283221461027b57806341c0e1b51461029b57806344169752146102b057806349a3d737146102c557806350c86de5146102e557806351c4a631146102fa576101bc565b8063040141e5146101c157806305a363de146101ec5780631e48907b1461020e5780631ec18ec01461022e5780632b6e65811461025b576101bc565b366101bc576000546001600160a01b03163314156101ba5773c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0476040518263ffffffff1660e01b81526004016000604051808303818588803b1580156101a057600080fd5b505af11580156101b4573d6000803e3d6000fd5b50505050505b005b600080fd5b3480156101cd57600080fd5b506101d6610422565b6040516101e39190611ebf565b60405180910390f35b3480156101f857600080fd5b5061020161043a565b6040516101e39190612061565b34801561021a57600080fd5b506101ba610229366004611aa6565b61043f565b34801561023a57600080fd5b5061024e610249366004611b4f565b610478565b6040516101e39190612070565b34801561026757600080fd5b5061024e610276366004611b4f565b6106bb565b34801561028757600080fd5b506101ba610296366004611c91565b610b8e565b3480156102a757600080fd5b506101ba610c2d565b3480156102bc57600080fd5b506101d6610c52565b3480156102d157600080fd5b506101ba6102e0366004611b4f565b610c6a565b3480156102f157600080fd5b5061024e610d20565b34801561030657600080fd5b506101ba610315366004611b87565b610d26565b34801561032657600080fd5b506101d6610da6565b34801561033b57600080fd5b506101d6610dbe565b34801561035057600080fd5b5061024e610dd6565b34801561036557600080fd5b506101ba610374366004611bc7565b610de2565b34801561038557600080fd5b506101d66116df565b34801561039a57600080fd5b506101d66116ee565b3480156103af57600080fd5b506101ba6103be366004611aa6565b611706565b3480156103cf57600080fd5b506101d661173f565b3480156103e457600080fd5b506101ba6103f3366004611aa6565b611757565b34801561040457600080fd5b506101d6611784565b34801561041957600080fd5b506101d6611793565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b604081565b6001546001600160a01b0316331461045657600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b1580156104c857600080fd5b505afa1580156104dc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105009190611ac9565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561055157600080fd5b505afa158015610565573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105899190611ac9565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b81526004016105b99190611ebf565b6101006040518083038186803b1580156105d257600080fd5b505afa1580156105e6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061060a9190611d99565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b81526004016106419190611ebf565b60206040518083038186803b15801561065957600080fd5b505afa15801561066d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106919190611cd8565b90506106ae6106a083836117ab565b670de05bc096e9c0006117dc565b9450505050505b92915050565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561070b57600080fd5b505afa15801561071f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107439190611ac9565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b15801561079457600080fd5b505afa1580156107a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107cc9190611ac9565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b15801561081d57600080fd5b505afa158015610831573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108559190611ac9565b90506000806000856001600160a01b0316632c6d0e9b896040518263ffffffff1660e01b81526004016108889190611ebf565b6101006040518083038186803b1580156108a157600080fd5b505afa1580156108b5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108d99190611d30565b50505094505093509350506000856001600160a01b0316635fc526ff8b6040518263ffffffff1660e01b81526004016109129190611ebf565b60806040518083038186803b15801561092a57600080fd5b505afa15801561093e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109629190611cf0565b50509150506000856001600160a01b031663b3596f078c6040518263ffffffff1660e01b81526004016109959190611ebf565b60206040518083038186803b1580156109ad57600080fd5b505afa1580156109c1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109e59190611cd8565b90506000876001600160a01b03166318a4dbca8d8d6040518363ffffffff1660e01b8152600401610a17929190611ed3565b60206040518083038186803b158015610a2f57600080fd5b505afa158015610a43573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a679190611cd8565b90506000610a7582846117dc565b905085610a8d575098506106b5975050505050505050565b6000610ab5610aaf610a9f888b611804565b610aaa8a6064611804565b611828565b87611838565b9050818111610ac45780610ac6565b815b9050878110610ae257879b5050505050505050505050506106b5565b6000610afb610af1888b6117dc565b610aaa88866117dc565b90506000610b2d610b1e83610b19610b138888611828565b8b6117dc565b611843565b610b288c86611828565b6117ab565b905087811015610b6c57610b58610b52610b47838d611804565b610aaa8c6064611804565b82611838565b9250838311610b675782610b69565b835b92505b610b796106a084886117ab565b9d505050505050505050505050505092915050565b6000546001600160a01b03163314610ba557600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b0383161415610c0957600080546040516001600160a01b039091169183156108fc02918491818181858888f19350505050158015610c03573d6000803e3d6000fd5b50610c29565b600054610c29906001600160a01b0384811691168363ffffffff61185316565b5050565b6000546001600160a01b03163314610c4457600080fd5b6000546001600160a01b0316ff5b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415610c9f57610c9a828247610d26565b610c29565b610c298282846001600160a01b03166370a08231306040518263ffffffff1660e01b8152600401610cd09190611ebf565b60206040518083038186803b158015610ce857600080fd5b505afa158015610cfc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103159190611cd8565b61019081565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415610d87576040516001600160a01b0383169082156108fc029083906000818181858888f19350505050158015610d81573d6000803e3d6000fd5b50610da1565b610da16001600160a01b038416838363ffffffff61185316565b505050565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b731b14e8d511c9a4395425314f849bd737baf8208f81565b670de05bc096e9c00081565b600080600080600085806020019051810190610dfe9190611ae5565b604051632e1a7d4d60e01b815294995092975090955093509150819073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc290632e1a7d4d90610e44908790600401612070565b600060405180830381600087803b158015610e5e57600080fd5b505af1158015610e72573d6000803e3d6000fd5b5050505060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015610ec557600080fd5b505afa158015610ed9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610efd9190611ac9565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610f4e57600080fd5b505afa158015610f62573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f869190611ac9565b90506000826001600160a01b03166334b3beee8a6040518263ffffffff1660e01b8152600401610fb69190611ebf565b60206040518083038186803b158015610fce57600080fd5b505afa158015610fe2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110069190611ac9565b90506000836001600160a01b03166334b3beee8a6040518263ffffffff1660e01b81526004016110369190611ebf565b60206040518083038186803b15801561104e57600080fd5b505afa158015611062573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110869190611ac9565b9050846001600160a01b0316631cff79cd89739d266997bc73b27d4302e711b55fd78b5278e1de73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee8c6040516024016110d4929190611f93565b60408051601f198184030181529181526020820180516001600160e01b03166311f9fbc960e21b1790525160e085901b6001600160e01b031916815261111e929190600401611f6f565b6020604051808303818588803b15801561113757600080fd5b505af115801561114b573d6000803e3d6000fd5b50505050506040513d601f19601f820116820180604052508101906111709190611cd8565b50600080846001600160a01b03166328dd2d018c8b6040518363ffffffff1660e01b81526004016111a2929190611ed3565b6101406040518083038186803b1580156111bb57600080fd5b505afa1580156111cf573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111f39190611df5565b505050505050935050925050866001600160a01b0316631cff79cd739d266997bc73b27d4302e711b55fd78b5278e1de8d858560405160240161123893929190611fac565b60408051601f198184030181529181526020820180516001600160e01b031663c1bce0b760e01b1790525160e084901b6001600160e01b0319168152611282929190600401611f6f565b602060405180830381600087803b15801561129c57600080fd5b505af11580156112b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112d49190611cd8565b506112ef6001600160a01b038c16898463ffffffff6118a916565b866001600160a01b0316631cff79cd739d266997bc73b27d4302e711b55fd78b5278e1de8d86600060018f60405160240161132e959493929190611eed565b60408051601f198184030181529181526020820180516001600160e01b0316630989052760e11b1790525160e084901b6001600160e01b0319168152611378929190600401611f6f565b602060405180830381600087803b15801561139257600080fd5b505af11580156113a6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113ca9190611cd8565b506040516370a0823160e01b81526000906001600160a01b038616906370a08231906113fa908d90600401611ebf565b60206040518083038186803b15801561141257600080fd5b505afa158015611426573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061144a9190611cd8565b90506114676001600160a01b0386168b8b8463ffffffff6118c816565b876001600160a01b0316631cff79cd739d266997bc73b27d4302e711b55fd78b5278e1de8f60405160240161149c9190611ebf565b60408051601f198184030181529181526020820180516001600160e01b0316636d1b72df60e11b1790525160e084901b6001600160e01b03191681526114e6929190600401611f6f565b602060405180830381600087803b15801561150057600080fd5b505af1158015611514573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115389190611cd8565b50876001600160a01b0316631cff79cd739d266997bc73b27d4302e711b55fd78b5278e1de73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee733a3a65aab0dd2a17e3f1947ba16138cd37d08c048f600060405160240161159d9493929190611f46565b60408051601f198184030181529181526020820180516001600160e01b031663934785b760e01b1790525160e084901b6001600160e01b03191681526115e7929190600401611f6f565b602060405180830381600087803b15801561160157600080fd5b505af1158015611615573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116399190611cd8565b5073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc26001600160a01b031663d0e30db0476040518263ffffffff1660e01b81526004016000604051808303818588803b15801561168957600080fd5b505af115801561169d573d6000803e3d6000fd5b506116cd935073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc292508c91505060028e0163ffffffff61185316565b50505050505050505050505050505050565b6000546001600160a01b031681565b733a3a65aab0dd2a17e3f1947ba16138cd37d08c0481565b6001546001600160a01b0316331461171d57600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b7324a42fd28c976a61df5d00d0599c34c4f90748c881565b6000546001600160a01b0316331461176e57600080fd5b6001546001600160a01b03161561171d57600080fd5b6001546001600160a01b031681565b739d266997bc73b27d4302e711b55fd78b5278e1de81565b6000816117cd6117c385670de0b6b3a7640000611804565b6002855b04611843565b816117d457fe5b049392505050565b6000670de0b6b3a76400006117cd6117f48585611804565b6002670de0b6b3a76400006117c7565b600081158061181f5750508082028282828161181c57fe5b04145b6106b557600080fd5b808203828111156106b557600080fd5b60008183816117d457fe5b808201828110156106b557600080fd5b610da18363a9059cbb60e01b8484604051602401611872929190611f93565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526118ef565b610da18363095ea7b360e01b8484604051602401611872929190611f93565b6118e9846323b872dd60e01b85858560405160240161187293929190611f22565b50505050565b6060611944826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166119879092919063ffffffff16565b805190915015610da157808060200190518101906119629190611cbc565b610da15760405162461bcd60e51b815260040161197e90612017565b60405180910390fd5b6060611996848460008561199e565b949350505050565b60606119a985611a62565b6119c55760405162461bcd60e51b815260040161197e90611fe0565b60006060866001600160a01b031685876040516119e29190611ea3565b60006040518083038185875af1925050503d8060008114611a1f576040519150601f19603f3d011682016040523d82523d6000602084013e611a24565b606091505b50915091508115611a385791506119969050565b805115611a485780518082602001fd5b8360405162461bcd60e51b815260040161197e9190611fcd565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611996575050151592915050565b80356106b5816120fc565b600060208284031215611ab7578081fd5b8135611ac2816120fc565b9392505050565b600060208284031215611ada578081fd5b8151611ac2816120fc565b600080600080600060a08688031215611afc578081fd5b8551611b07816120fc565b6020870151909550611b18816120fc565b604087015160608801519195509350611b30816120fc565b6080870151909250611b41816120fc565b809150509295509295909350565b60008060408385031215611b61578182fd5b8235611b6c816120fc565b91506020830135611b7c816120fc565b809150509250929050565b600080600060608486031215611b9b578283fd5b8335611ba6816120fc565b92506020840135611bb6816120fc565b929592945050506040919091013590565b60008060008385036080811215611bdc578384fd5b8435611be7816120fc565b93506040601f1982011215611bfa578283fd5b50611c056040612079565b611c128660208701611a9b565b8152604085013560208201529150606084013567ffffffffffffffff811115611c39578182fd5b80850186601f820112611c4a578283fd5b80359150611c5f611c5a836120a0565b612079565b828152876020848401011115611c73578384fd5b611c848360208301602085016120c4565b8093505050509250925092565b60008060408385031215611ca3578182fd5b8235611cae816120fc565b946020939093013593505050565b600060208284031215611ccd578081fd5b8151611ac281612114565b600060208284031215611ce9578081fd5b5051919050565b60008060008060808587031215611d05578384fd5b8451935060208501519250604085015191506060850151611d2581612114565b939692955090935050565b600080600080600080600080610100898b031215611d4c578283fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e0890151611d8881612114565b809150509295985092959890939650565b600080600080600080600080610100898b031215611db5578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6000806000806000806000806000806101408b8d031215611e14578384fd5b8a51995060208b0151985060408b0151975060608b0151965060808b0151955060a08b0151945060c08b0151935060e08b015192506101008b015191506101208b01518015158114611e64578182fd5b809150509295989b9194979a5092959850565b60008151808452611e8f8160208601602086016120d0565b601f01601f19169290920160200192915050565b60008251611eb58184602087016120d0565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039586168152938516602085015260ff92909216604084015215156060830152909116608082015260a00190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b0394851681529290931660208301526040820152901515606082015260800190565b6001600160a01b038316815260406020820181905260009061199690830184611e77565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039390931683526020830191909152604082015260600190565b600060208252611ac26020830184611e77565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b61ffff91909116815260200190565b90815260200190565b60405181810167ffffffffffffffff8111828210171561209857600080fd5b604052919050565b600067ffffffffffffffff8211156120b6578081fd5b50601f01601f191660200190565b82818337506000910152565b60005b838110156120eb5781810151838201526020016120d3565b838111156118e95750506000910152565b6001600160a01b038116811461211157600080fd5b50565b801515811461211157600080fdfea2646970667358221220a57aa3b923a5c0563f14b878f8423b0fa8f954589401a6f27e521351bfc5969564736f6c63430006060033
[ 37, 17, 11, 8, 9, 12, 16, 5, 2 ]
0x572f42272e6028e4088318b2ecc98ae0d2eeab27
pragma solidity 0.5.17; library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } 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; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } }
0x60806040526004361061004a5760003560e01c80632c4e722e1461005c5780634042b66f14610083578063521eb27314610098578063ec8ac4d8146100c9578063fc0c546a146100ef575b61005a610055610104565b610108565b005b34801561006857600080fd5b5061007161022a565b60408051918252519081900360200190f35b34801561008f57600080fd5b50610071610230565b3480156100a457600080fd5b506100ad610236565b604080516001600160a01b039092168252519081900360200190f35b61005a600480360360208110156100df57600080fd5b50356001600160a01b0316610108565b3480156100fb57600080fd5b506100ad610245565b3390565b60005460ff1661015f576040805162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015290519081900360640190fd5b6000805460ff19169055346101748282610259565b600061017f826102f4565b600354909150610195908363ffffffff61031116565b6003556101a28382610372565b826001600160a01b03166101b4610104565b6001600160a01b03167f6faf93231a456e552dbc9961f58d9713ee4f2e69d15f1975b050ef0911053a7b8484604051808381526020018281526020019250505060405180910390a361020683836102f0565b61020e61037c565b61021883836102f0565b50506000805460ff1916600117905550565b60025490565b60035490565b6001546001600160a01b031690565b60005461010090046001600160a01b031690565b6001600160a01b03821661029e5760405162461bcd60e51b815260040180806020018281038252602a81526020018061069b602a913960400191505060405180910390fd5b806102f0576040805162461bcd60e51b815260206004820152601960248201527f43726f776473616c653a20776569416d6f756e74206973203000000000000000604482015290519081900360640190fd5b5050565b600061030b600254836103b890919063ffffffff16565b92915050565b60008282018381101561036b576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6102f08282610411565b6001546040516001600160a01b03909116903480156108fc02916000818181858888f193505050501580156103b5573d6000803e3d6000fd5b50565b6000826103c75750600061030b565b828202828482816103d457fe5b041461036b5760405162461bcd60e51b815260040180806020018281038252602181526020018061067a6021913960400191505060405180910390fd5b6000546102f09061010090046001600160a01b03168383604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b17905261047a90849061047f565b505050565b610491826001600160a01b031661063d565b6104e2576040805162461bcd60e51b815260206004820152601f60248201527f5361666545524332303a2063616c6c20746f206e6f6e2d636f6e747261637400604482015290519081900360640190fd5b60006060836001600160a01b0316836040518082805190602001908083835b602083106105205780518252601f199092019160209182019101610501565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114610582576040519150601f19603f3d011682016040523d82523d6000602084013e610587565b606091505b5091509150816105de576040805162461bcd60e51b815260206004820181905260248201527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564604482015290519081900360640190fd5b805115610637578080602001905160208110156105fa57600080fd5b50516106375760405162461bcd60e51b815260040180806020018281038252602a8152602001806106c5602a913960400191505060405180910390fd5b50505050565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061067157508115155b94935050505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7743726f776473616c653a2062656e656669636961727920697320746865207a65726f20616464726573735361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a265627a7a72315820a8ea17df613435e58eec346a5f782b7a8e1c25a21a914f8b803b482e4aba89f064736f6c63430005110032
[ 38 ]
0x577acf90e357300262210a17ac69efffbd2cba3c
pragma solidity 0.7.0; library AdditionalMath { using SafeMath for uint256; function max16(uint16 a, uint16 b) internal pure returns (uint16) { return a >= b ? a : b; } function min16(uint16 a, uint16 b) internal pure returns (uint16) { return a < b ? a : b; } /** * @notice Division and ceil */ function divCeil(uint256 a, uint256 b) internal pure returns (uint256) { return (a.add(b) - 1) / b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.add(uint256(b)); } else { return a.sub(uint256(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned(uint256 a, int256 b) internal pure returns (uint256) { if (b >= 0) { return a.sub(uint256(b)); } else { return a.add(uint256(-b)); } } /** * @dev Multiplies two numbers, throws on overflow. */ function mul32(uint32 a, uint32 b) internal pure returns (uint32) { if (a == 0) { return 0; } uint32 c = a * b; assert(c / a == b); return c; } /** * @dev Adds two numbers, throws on overflow. */ function add16(uint16 a, uint16 b) internal pure returns (uint16) { uint16 c = a + b; assert(c >= a); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub16(uint16 a, uint16 b) internal pure returns (uint16) { assert(b <= a); return a - b; } /** * @dev Adds signed value to unsigned value, throws on overflow. */ function addSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return add16(a, uint16(b)); } else { return sub16(a, uint16(-b)); } } /** * @dev Subtracts signed value from unsigned value, throws on overflow. */ function subSigned16(uint16 a, int16 b) internal pure returns (uint16) { if (b >= 0) { return sub16(a, uint16(b)); } else { return add16(a, uint16(-b)); } } } 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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } } library Bits { uint256 internal constant ONE = uint256(1); /** * @notice Sets the bit at the given 'index' in 'self' to: * '1' - if the bit is '0' * '0' - if the bit is '1' * @return The modified value */ function toggleBit(uint256 self, uint8 index) internal pure returns (uint256) { return self ^ ONE << index; } /** * @notice Get the value of the bit at the given 'index' in 'self'. */ function bit(uint256 self, uint8 index) internal pure returns (uint8) { return uint8(self >> index & 1); } /** * @notice Check if the bit at the given 'index' in 'self' is set. * @return 'true' - if the value of the bit is '1', * 'false' - if the value of the bit is '0' */ function bitSet(uint256 self, uint8 index) internal pure returns (bool) { return self >> index & 1 == 1; } } interface ERCProxy { function proxyType() external pure returns (uint256); function implementation() external view returns (address); } 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); } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view override returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { // 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 require(value == 0 || _allowed[msg.sender][spender] == 0); _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } interface IERC900History { function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256); function totalStakedAt(uint256 blockNumber) external view returns (uint256); function supportsHistory() external pure returns (bool); } 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 Calculates the average of two numbers. Since these are integers, * averages of an even and odd number cannot be represented, and will be * rounded down. */ 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); } } contract NuCypherToken is ERC20, ERC20Detailed('NuCypher', 'NU', 18) { /** * @notice Set amount of tokens * @param _totalSupplyOfTokens Total number of tokens */ constructor (uint256 _totalSupplyOfTokens) { _mint(msg.sender, _totalSupplyOfTokens); } /** * @notice Approves and then calls the receiving contract * * @dev call the receiveApproval function on the contract you want to be notified. * receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) */ function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { approve(_spender, _value); TokenRecipient(_spender).receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } interface TokenRecipient { /** * @notice Receives a notification of approval of the transfer * @param _from Sender of approval * @param _value The amount of tokens to be spent * @param _tokenContract Address of the token contract * @param _extraData Extra data */ function receiveApproval(address _from, uint256 _value, address _tokenContract, bytes calldata _extraData) external; } abstract contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library ReEncryptionValidator { using UmbralDeserializer for bytes; //------------------------------// // Umbral-specific constants // //------------------------------// // See parameter `u` of `UmbralParameters` class in pyUmbral // https://github.com/nucypher/pyUmbral/blob/master/umbral/params.py uint8 public constant UMBRAL_PARAMETER_U_SIGN = 0x02; uint256 public constant UMBRAL_PARAMETER_U_XCOORD = 0x03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f; uint256 public constant UMBRAL_PARAMETER_U_YCOORD = 0x7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936; //------------------------------// // SECP256K1-specific constants // //------------------------------// // Base field order uint256 constant FIELD_ORDER = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; // -2 mod FIELD_ORDER uint256 constant MINUS_2 = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2d; // (-1/2) mod FIELD_ORDER uint256 constant MINUS_ONE_HALF = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffe17; // /** * @notice Check correctness of re-encryption * @param _capsuleBytes Capsule * @param _cFragBytes Capsule frag * @param _precomputedBytes Additional precomputed data */ function validateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _precomputedBytes ) internal pure returns (bool) { UmbralDeserializer.Capsule memory _capsule = _capsuleBytes.toCapsule(); UmbralDeserializer.CapsuleFrag memory _cFrag = _cFragBytes.toCapsuleFrag(); UmbralDeserializer.PreComputedData memory _precomputed = _precomputedBytes.toPreComputedData(); // Extract Alice's address and check that it corresponds to the one provided address alicesAddress = SignatureVerifier.recover( _precomputed.hashedKFragValidityMessage, abi.encodePacked(_cFrag.proof.kFragSignature, _precomputed.lostBytes[0]) ); require(alicesAddress == _precomputed.alicesKeyAsAddress, "Bad KFrag signature"); // Compute proof's challenge scalar h, used in all ZKP verification equations uint256 h = computeProofChallengeScalar(_capsule, _cFrag); ////// // Verifying 1st equation: z*E == h*E_1 + E_2 ////// // Input validation: E require(checkCompressedPoint( _capsule.pointE.sign, _capsule.pointE.xCoord, _precomputed.pointEyCoord), "Precomputed Y coordinate of E doesn't correspond to compressed E point" ); // Input validation: z*E require(isOnCurve(_precomputed.pointEZxCoord, _precomputed.pointEZyCoord), "Point zE is not a valid EC point" ); require(ecmulVerify( _capsule.pointE.xCoord, // E_x _precomputed.pointEyCoord, // E_y _cFrag.proof.bnSig, // z _precomputed.pointEZxCoord, // zE_x _precomputed.pointEZyCoord), // zE_y "Precomputed z*E value is incorrect" ); // Input validation: E1 require(checkCompressedPoint( _cFrag.pointE1.sign, // E1_sign _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord), // E1_y "Precomputed Y coordinate of E1 doesn't correspond to compressed E1 point" ); // Input validation: h*E1 require(isOnCurve(_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord), "Point h*E1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointE1.xCoord, // E1_x _precomputed.pointE1yCoord, // E1_y h, _precomputed.pointE1HxCoord, // hE1_x _precomputed.pointE1HyCoord), // hE1_y "Precomputed h*E1 value is incorrect" ); // Input validation: E2 require(checkCompressedPoint( _cFrag.proof.pointE2.sign, // E2_sign _cFrag.proof.pointE2.xCoord, // E2_x _precomputed.pointE2yCoord), // E2_y "Precomputed Y coordinate of E2 doesn't correspond to compressed E2 point" ); bool equation_holds = eqAffineJacobian( [_precomputed.pointEZxCoord, _precomputed.pointEZyCoord], addAffineJacobian( [_cFrag.proof.pointE2.xCoord, _precomputed.pointE2yCoord], [_precomputed.pointE1HxCoord, _precomputed.pointE1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 2nd equation: z*V == h*V_1 + V_2 ////// // Input validation: V require(checkCompressedPoint( _capsule.pointV.sign, _capsule.pointV.xCoord, _precomputed.pointVyCoord), "Precomputed Y coordinate of V doesn't correspond to compressed V point" ); // Input validation: z*V require(isOnCurve(_precomputed.pointVZxCoord, _precomputed.pointVZyCoord), "Point zV is not a valid EC point" ); require(ecmulVerify( _capsule.pointV.xCoord, // V_x _precomputed.pointVyCoord, // V_y _cFrag.proof.bnSig, // z _precomputed.pointVZxCoord, // zV_x _precomputed.pointVZyCoord), // zV_y "Precomputed z*V value is incorrect" ); // Input validation: V1 require(checkCompressedPoint( _cFrag.pointV1.sign, // V1_sign _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord), // V1_y "Precomputed Y coordinate of V1 doesn't correspond to compressed V1 point" ); // Input validation: h*V1 require(isOnCurve(_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord), "Point h*V1 is not a valid EC point" ); require(ecmulVerify( _cFrag.pointV1.xCoord, // V1_x _precomputed.pointV1yCoord, // V1_y h, _precomputed.pointV1HxCoord, // h*V1_x _precomputed.pointV1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: V2 require(checkCompressedPoint( _cFrag.proof.pointV2.sign, // V2_sign _cFrag.proof.pointV2.xCoord, // V2_x _precomputed.pointV2yCoord), // V2_y "Precomputed Y coordinate of V2 doesn't correspond to compressed V2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointVZxCoord, _precomputed.pointVZyCoord], addAffineJacobian( [_cFrag.proof.pointV2.xCoord, _precomputed.pointV2yCoord], [_precomputed.pointV1HxCoord, _precomputed.pointV1HyCoord] ) ); if (!equation_holds){ return false; } ////// // Verifying 3rd equation: z*U == h*U_1 + U_2 ////// // We don't have to validate U since it's fixed and hard-coded // Input validation: z*U require(isOnCurve(_precomputed.pointUZxCoord, _precomputed.pointUZyCoord), "Point z*U is not a valid EC point" ); require(ecmulVerify( UMBRAL_PARAMETER_U_XCOORD, // U_x UMBRAL_PARAMETER_U_YCOORD, // U_y _cFrag.proof.bnSig, // z _precomputed.pointUZxCoord, // zU_x _precomputed.pointUZyCoord), // zU_y "Precomputed z*U value is incorrect" ); // Input validation: U1 (a.k.a. KFragCommitment) require(checkCompressedPoint( _cFrag.proof.pointKFragCommitment.sign, // U1_sign _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord), // U1_y "Precomputed Y coordinate of U1 doesn't correspond to compressed U1 point" ); // Input validation: h*U1 require(isOnCurve(_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord), "Point h*U1 is not a valid EC point" ); require(ecmulVerify( _cFrag.proof.pointKFragCommitment.xCoord, // U1_x _precomputed.pointU1yCoord, // U1_y h, _precomputed.pointU1HxCoord, // h*V1_x _precomputed.pointU1HyCoord), // h*V1_y "Precomputed h*V1 value is incorrect" ); // Input validation: U2 (a.k.a. KFragPok ("proof of knowledge")) require(checkCompressedPoint( _cFrag.proof.pointKFragPok.sign, // U2_sign _cFrag.proof.pointKFragPok.xCoord, // U2_x _precomputed.pointU2yCoord), // U2_y "Precomputed Y coordinate of U2 doesn't correspond to compressed U2 point" ); equation_holds = eqAffineJacobian( [_precomputed.pointUZxCoord, _precomputed.pointUZyCoord], addAffineJacobian( [_cFrag.proof.pointKFragPok.xCoord, _precomputed.pointU2yCoord], [_precomputed.pointU1HxCoord, _precomputed.pointU1HyCoord] ) ); return equation_holds; } function computeProofChallengeScalar( UmbralDeserializer.Capsule memory _capsule, UmbralDeserializer.CapsuleFrag memory _cFrag ) internal pure returns (uint256) { // Compute h = hash_to_bignum(e, e1, e2, v, v1, v2, u, u1, u2, metadata) bytes memory hashInput = abi.encodePacked( // Point E _capsule.pointE.sign, _capsule.pointE.xCoord, // Point E1 _cFrag.pointE1.sign, _cFrag.pointE1.xCoord, // Point E2 _cFrag.proof.pointE2.sign, _cFrag.proof.pointE2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point V _capsule.pointV.sign, _capsule.pointV.xCoord, // Point V1 _cFrag.pointV1.sign, _cFrag.pointV1.xCoord, // Point V2 _cFrag.proof.pointV2.sign, _cFrag.proof.pointV2.xCoord ); hashInput = abi.encodePacked( hashInput, // Point U bytes1(UMBRAL_PARAMETER_U_SIGN), bytes32(UMBRAL_PARAMETER_U_XCOORD), // Point U1 _cFrag.proof.pointKFragCommitment.sign, _cFrag.proof.pointKFragCommitment.xCoord, // Point U2 _cFrag.proof.pointKFragPok.sign, _cFrag.proof.pointKFragPok.xCoord, // Re-encryption metadata _cFrag.proof.metadata ); uint256 h = extendedKeccakToBN(hashInput); return h; } function extendedKeccakToBN (bytes memory _data) internal pure returns (uint256) { bytes32 upper; bytes32 lower; // Umbral prepends to the data a customization string of 64-bytes. // In the case of hash_to_curvebn is 'hash_to_curvebn', padded with zeroes. bytes memory input = abi.encodePacked(bytes32("hash_to_curvebn"), bytes32(0x00), _data); (upper, lower) = (keccak256(abi.encodePacked(uint8(0x00), input)), keccak256(abi.encodePacked(uint8(0x01), input))); // Let n be the order of secp256k1's group (n = 2^256 - 0x1000003D1) // n_minus_1 = n - 1 // delta = 2^256 mod n_minus_1 uint256 delta = 0x14551231950b75fc4402da1732fc9bec0; uint256 n_minus_1 = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140; uint256 upper_half = mulmod(uint256(upper), delta, n_minus_1); return 1 + addmod(upper_half, uint256(lower), n_minus_1); } /// @notice Tests if a compressed point is valid, wrt to its corresponding Y coordinate /// @param _pointSign The sign byte from the compressed notation: 0x02 if the Y coord is even; 0x03 otherwise /// @param _pointX The X coordinate of an EC point in affine representation /// @param _pointY The Y coordinate of an EC point in affine representation /// @return true iff _pointSign and _pointX are the compressed representation of (_pointX, _pointY) function checkCompressedPoint( uint8 _pointSign, uint256 _pointX, uint256 _pointY ) internal pure returns(bool) { bool correct_sign = _pointY % 2 == _pointSign - 2; return correct_sign && isOnCurve(_pointX, _pointY); } /// @notice Tests if the given serialized coordinates represent a valid EC point /// @param _coords The concatenation of serialized X and Y coordinates /// @return true iff coordinates X and Y are a valid point function checkSerializedCoordinates(bytes memory _coords) internal pure returns(bool) { require(_coords.length == 64, "Serialized coordinates should be 64 B"); uint256 coordX; uint256 coordY; assembly { coordX := mload(add(_coords, 32)) coordY := mload(add(_coords, 64)) } return isOnCurve(coordX, coordY); } /// @notice Tests if a point is on the secp256k1 curve /// @param Px The X coordinate of an EC point in affine representation /// @param Py The Y coordinate of an EC point in affine representation /// @return true if (Px, Py) is a valid secp256k1 point; false otherwise function isOnCurve(uint256 Px, uint256 Py) internal pure returns (bool) { uint256 p = FIELD_ORDER; if (Px >= p || Py >= p){ return false; } uint256 y2 = mulmod(Py, Py, p); uint256 x3_plus_7 = addmod(mulmod(mulmod(Px, Px, p), Px, p), 7, p); return y2 == x3_plus_7; } // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/4 function ecmulVerify( uint256 x1, uint256 y1, uint256 scalar, uint256 qx, uint256 qy ) internal pure returns(bool) { uint256 curve_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; address signer = ecrecover(0, uint8(27 + (y1 % 2)), bytes32(x1), bytes32(mulmod(scalar, x1, curve_order))); address xyAddress = address(uint256(keccak256(abi.encodePacked(qx, qy))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return xyAddress == signer; } /// @notice Equality test of two points, in affine and Jacobian coordinates respectively /// @param P An EC point in affine coordinates /// @param Q An EC point in Jacobian coordinates /// @return true if P and Q represent the same point in affine coordinates; false otherwise function eqAffineJacobian( uint256[2] memory P, uint256[3] memory Q ) internal pure returns(bool){ uint256 Qz = Q[2]; if(Qz == 0){ return false; // Q is zero but P isn't. } uint256 p = FIELD_ORDER; uint256 Q_z_squared = mulmod(Qz, Qz, p); return mulmod(P[0], Q_z_squared, p) == Q[0] && mulmod(P[1], mulmod(Q_z_squared, Qz, p), p) == Q[1]; } /// @notice Adds two points in affine coordinates, with the result in Jacobian /// @dev Based on the addition formulas from http://www.hyperelliptic.org/EFD/g1p/auto-code/shortw/jacobian-0/addition/add-2001-b.op3 /// @param P An EC point in affine coordinates /// @param Q An EC point in affine coordinates /// @return R An EC point in Jacobian coordinates with the sum, represented by an array of 3 uint256 function addAffineJacobian( uint[2] memory P, uint[2] memory Q ) internal pure returns (uint[3] memory R) { uint256 p = FIELD_ORDER; uint256 a = P[0]; uint256 c = P[1]; uint256 t0 = Q[0]; uint256 t1 = Q[1]; if ((a == t0) && (c == t1)){ return doubleJacobian([a, c, 1]); } uint256 d = addmod(t1, p-c, p); // d = t1 - c uint256 b = addmod(t0, p-a, p); // b = t0 - a uint256 e = mulmod(b, b, p); // e = b^2 uint256 f = mulmod(e, b, p); // f = b^3 uint256 g = mulmod(a, e, p); R[0] = addmod(mulmod(d, d, p), p-addmod(mulmod(2, g, p), f, p), p); R[1] = addmod(mulmod(d, addmod(g, p-R[0], p), p), p-mulmod(c, f, p), p); R[2] = b; } /// @notice Point doubling in Jacobian coordinates /// @param P An EC point in Jacobian coordinates. /// @return Q An EC point in Jacobian coordinates function doubleJacobian(uint[3] memory P) internal pure returns (uint[3] memory Q) { uint256 z = P[2]; if (z == 0) return Q; uint256 p = FIELD_ORDER; uint256 x = P[0]; uint256 _2y = mulmod(2, P[1], p); uint256 _4yy = mulmod(_2y, _2y, p); uint256 s = mulmod(_4yy, x, p); uint256 m = mulmod(3, mulmod(x, x, p), p); uint256 t = addmod(mulmod(m, m, p), mulmod(MINUS_2, s, p),p); Q[0] = t; Q[1] = addmod(mulmod(m, addmod(s, p - t, p), p), mulmod(MINUS_ONE_HALF, mulmod(_4yy, _4yy, p), p), p); Q[2] = mulmod(_2y, z, p); } } library SafeERC20 { using SafeMath for uint256; function safeTransfer(IERC20 token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { require(token.transferFrom(from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // 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(msg.sender, spender) == 0)); require(token.approve(spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); require(token.approve(spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); require(token.approve(spender, newAllowance)); } } library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } library SignatureVerifier { enum HashAlgorithm {KECCAK256, SHA256, RIPEMD160} // Header for Version E as defined by EIP191. First byte ('E') is also the version bytes25 constant EIP191_VERSION_E_HEADER = "Ethereum Signed Message:\n"; /** * @notice Recover signer address from hash and signature * @param _hash 32 bytes message hash * @param _signature Signature of hash - 32 bytes r + 32 bytes s + 1 byte v (could be 0, 1, 27, 28) */ function recover(bytes32 _hash, bytes memory _signature) internal pure returns (address) { require(_signature.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(_signature, 32)) s := mload(add(_signature, 64)) v := byte(0, mload(add(_signature, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); return ecrecover(_hash, v, r, s); } /** * @notice Transform public key to address * @param _publicKey secp256k1 public key */ function toAddress(bytes memory _publicKey) internal pure returns (address) { return address(uint160(uint256(keccak256(_publicKey)))); } /** * @notice Hash using one of pre built hashing algorithm * @param _message Signed message * @param _algorithm Hashing algorithm */ function hash(bytes memory _message, HashAlgorithm _algorithm) internal pure returns (bytes32 result) { if (_algorithm == HashAlgorithm.KECCAK256) { result = keccak256(_message); } else if (_algorithm == HashAlgorithm.SHA256) { result = sha256(_message); } else { result = ripemd160(_message); } } /** * @notice Verify ECDSA signature * @dev Uses one of pre built hashing algorithm * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _algorithm Hashing algorithm */ function verify( bytes memory _message, bytes memory _signature, bytes memory _publicKey, HashAlgorithm _algorithm ) internal pure returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hash(_message, _algorithm), _signature); } /** * @notice Hash message according to EIP191 signature specification * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Message to sign * @param _version EIP191 version to use */ function hashEIP191( bytes memory _message, byte _version ) internal view returns (bytes32 result) { if(_version == byte(0x00)){ // Version 0: Data with intended validator address validator = address(this); return keccak256(abi.encodePacked(byte(0x19), byte(0x00), validator, _message)); } else if (_version == byte(0x45)){ // Version E: personal_sign messages uint256 length = _message.length; require(length > 0, "Empty message not allowed for version E"); // Compute text-encoded length of message uint256 digits = 0; while (length != 0) { digits++; length /= 10; } bytes memory lengthAsText = new bytes(digits); length = _message.length; uint256 index = digits - 1; while (length != 0) { lengthAsText[index--] = byte(uint8(48 + length % 10)); length /= 10; } return keccak256(abi.encodePacked(byte(0x19), EIP191_VERSION_E_HEADER, lengthAsText, _message)); } else { revert("Unsupported EIP191 version"); } } /** * @notice Verify EIP191 signature * @dev It always assumes Keccak256 is used as hashing algorithm * @dev Only supports version 0 and version E (0x45) * @param _message Signed message * @param _signature Signature of message hash * @param _publicKey secp256k1 public key in uncompressed format without prefix byte (64 bytes) * @param _version EIP191 version to use */ function verifyEIP191( bytes memory _message, bytes memory _signature, bytes memory _publicKey, byte _version ) internal view returns (bool) { require(_publicKey.length == 64); return toAddress(_publicKey) == recover(hashEIP191(_message, _version), _signature); } } library Snapshot { function encodeSnapshot(uint32 _time, uint96 _value) internal pure returns(uint128) { return uint128(uint256(_time) << 96 | uint256(_value)); } function decodeSnapshot(uint128 _snapshot) internal pure returns(uint32 time, uint96 value){ time = uint32(bytes4(bytes16(_snapshot))); value = uint96(_snapshot); } function addSnapshot(uint128[] storage _self, uint256 _value) internal { addSnapshot(_self, block.number, _value); } function addSnapshot(uint128[] storage _self, uint256 _time, uint256 _value) internal { uint256 length = _self.length; if (length != 0) { (uint32 currentTime, ) = decodeSnapshot(_self[length - 1]); if (uint32(_time) == currentTime) { _self[length - 1] = encodeSnapshot(uint32(_time), uint96(_value)); return; } else if (uint32(_time) < currentTime){ revert(); } } _self.push(encodeSnapshot(uint32(_time), uint96(_value))); } function lastSnapshot(uint128[] storage _self) internal view returns (uint32, uint96) { uint256 length = _self.length; if (length > 0) { return decodeSnapshot(_self[length - 1]); } return (0, 0); } function lastValue(uint128[] storage _self) internal view returns (uint96) { (, uint96 value) = lastSnapshot(_self); return value; } function getValueAt(uint128[] storage _self, uint256 _time256) internal view returns (uint96) { uint32 _time = uint32(_time256); uint256 length = _self.length; // Short circuit if there's no checkpoints yet // Note that this also lets us avoid using SafeMath later on, as we've established that // there must be at least one checkpoint if (length == 0) { return 0; } // Check last checkpoint uint256 lastIndex = length - 1; (uint32 snapshotTime, uint96 snapshotValue) = decodeSnapshot(_self[length - 1]); if (_time >= snapshotTime) { return snapshotValue; } // Check first checkpoint (if not already checked with the above check on last) (snapshotTime, snapshotValue) = decodeSnapshot(_self[0]); if (length == 1 || _time < snapshotTime) { return 0; } // Do binary search // As we've already checked both ends, we don't need to check the last checkpoint again uint256 low = 0; uint256 high = lastIndex - 1; uint32 midTime; uint96 midValue; while (high > low) { uint256 mid = (high + low + 1) / 2; // average, ceil round (midTime, midValue) = decodeSnapshot(_self[mid]); if (_time > midTime) { low = mid; } else if (_time < midTime) { // Note that we don't need SafeMath here because mid must always be greater than 0 // from the while condition high = mid - 1; } else { // _time == midTime return midValue; } } (, snapshotValue) = decodeSnapshot(_self[low]); return snapshotValue; } } interface PolicyManagerInterface { function register(address _node, uint16 _period) external; function updateFee(address _node, uint16 _period) external; function escrow() external view returns (address); function setDefaultFeeDelta(address _node, uint16 _period) external; } interface AdjudicatorInterface { function escrow() external view returns (address); } interface WorkLockInterface { function escrow() external view returns (address); } library UmbralDeserializer { struct Point { uint8 sign; uint256 xCoord; } struct Capsule { Point pointE; Point pointV; uint256 bnSig; } struct CorrectnessProof { Point pointE2; Point pointV2; Point pointKFragCommitment; Point pointKFragPok; uint256 bnSig; bytes kFragSignature; // 64 bytes bytes metadata; // any length } struct CapsuleFrag { Point pointE1; Point pointV1; bytes32 kFragId; Point pointPrecursor; CorrectnessProof proof; } struct PreComputedData { uint256 pointEyCoord; uint256 pointEZxCoord; uint256 pointEZyCoord; uint256 pointE1yCoord; uint256 pointE1HxCoord; uint256 pointE1HyCoord; uint256 pointE2yCoord; uint256 pointVyCoord; uint256 pointVZxCoord; uint256 pointVZyCoord; uint256 pointV1yCoord; uint256 pointV1HxCoord; uint256 pointV1HyCoord; uint256 pointV2yCoord; uint256 pointUZxCoord; uint256 pointUZyCoord; uint256 pointU1yCoord; uint256 pointU1HxCoord; uint256 pointU1HyCoord; uint256 pointU2yCoord; bytes32 hashedKFragValidityMessage; address alicesKeyAsAddress; bytes5 lostBytes; } uint256 constant BIGNUM_SIZE = 32; uint256 constant POINT_SIZE = 33; uint256 constant SIGNATURE_SIZE = 64; uint256 constant CAPSULE_SIZE = 2 * POINT_SIZE + BIGNUM_SIZE; uint256 constant CORRECTNESS_PROOF_SIZE = 4 * POINT_SIZE + BIGNUM_SIZE + SIGNATURE_SIZE; uint256 constant CAPSULE_FRAG_SIZE = 3 * POINT_SIZE + BIGNUM_SIZE; uint256 constant FULL_CAPSULE_FRAG_SIZE = CAPSULE_FRAG_SIZE + CORRECTNESS_PROOF_SIZE; uint256 constant PRECOMPUTED_DATA_SIZE = (20 * BIGNUM_SIZE) + 32 + 20 + 5; /** * @notice Deserialize to capsule (not activated) */ function toCapsule(bytes memory _capsuleBytes) internal pure returns (Capsule memory capsule) { require(_capsuleBytes.length == CAPSULE_SIZE); uint256 pointer = getPointer(_capsuleBytes); pointer = copyPoint(pointer, capsule.pointE); pointer = copyPoint(pointer, capsule.pointV); capsule.bnSig = uint256(getBytes32(pointer)); } /** * @notice Deserialize to correctness proof * @param _pointer Proof bytes memory pointer * @param _proofBytesLength Proof bytes length */ function toCorrectnessProof(uint256 _pointer, uint256 _proofBytesLength) internal pure returns (CorrectnessProof memory proof) { require(_proofBytesLength >= CORRECTNESS_PROOF_SIZE); _pointer = copyPoint(_pointer, proof.pointE2); _pointer = copyPoint(_pointer, proof.pointV2); _pointer = copyPoint(_pointer, proof.pointKFragCommitment); _pointer = copyPoint(_pointer, proof.pointKFragPok); proof.bnSig = uint256(getBytes32(_pointer)); _pointer += BIGNUM_SIZE; proof.kFragSignature = new bytes(SIGNATURE_SIZE); // TODO optimize, just two mload->mstore (#1500) _pointer = copyBytes(_pointer, proof.kFragSignature, SIGNATURE_SIZE); if (_proofBytesLength > CORRECTNESS_PROOF_SIZE) { proof.metadata = new bytes(_proofBytesLength - CORRECTNESS_PROOF_SIZE); copyBytes(_pointer, proof.metadata, proof.metadata.length); } } /** * @notice Deserialize to correctness proof */ function toCorrectnessProof(bytes memory _proofBytes) internal pure returns (CorrectnessProof memory proof) { uint256 pointer = getPointer(_proofBytes); return toCorrectnessProof(pointer, _proofBytes.length); } /** * @notice Deserialize to CapsuleFrag */ function toCapsuleFrag(bytes memory _cFragBytes) internal pure returns (CapsuleFrag memory cFrag) { uint256 cFragBytesLength = _cFragBytes.length; require(cFragBytesLength >= FULL_CAPSULE_FRAG_SIZE); uint256 pointer = getPointer(_cFragBytes); pointer = copyPoint(pointer, cFrag.pointE1); pointer = copyPoint(pointer, cFrag.pointV1); cFrag.kFragId = getBytes32(pointer); pointer += BIGNUM_SIZE; pointer = copyPoint(pointer, cFrag.pointPrecursor); cFrag.proof = toCorrectnessProof(pointer, cFragBytesLength - CAPSULE_FRAG_SIZE); } /** * @notice Deserialize to precomputed data */ function toPreComputedData(bytes memory _preComputedData) internal pure returns (PreComputedData memory data) { require(_preComputedData.length == PRECOMPUTED_DATA_SIZE); uint256 initial_pointer = getPointer(_preComputedData); uint256 pointer = initial_pointer; data.pointEyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointEZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointE2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointVZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointV2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointUZyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HxCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU1HyCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.pointU2yCoord = uint256(getBytes32(pointer)); pointer += BIGNUM_SIZE; data.hashedKFragValidityMessage = getBytes32(pointer); pointer += 32; data.alicesKeyAsAddress = address(bytes20(getBytes32(pointer))); pointer += 20; // Lost bytes: a bytes5 variable holding the following byte values: // 0: kfrag signature recovery value v // 1: cfrag signature recovery value v // 2: metadata signature recovery value v // 3: specification signature recovery value v // 4: ursula pubkey sign byte data.lostBytes = bytes5(getBytes32(pointer)); pointer += 5; require(pointer == initial_pointer + PRECOMPUTED_DATA_SIZE); } // TODO extract to external library if needed (#1500) /** * @notice Get the memory pointer for start of array */ function getPointer(bytes memory _bytes) internal pure returns (uint256 pointer) { assembly { pointer := add(_bytes, 32) // skip array length } } /** * @notice Copy point data from memory in the pointer position */ function copyPoint(uint256 _pointer, Point memory _point) internal pure returns (uint256 resultPointer) { // TODO optimize, copy to point memory directly (#1500) uint8 temp; uint256 xCoord; assembly { temp := byte(0, mload(_pointer)) xCoord := mload(add(_pointer, 1)) } _point.sign = temp; _point.xCoord = xCoord; resultPointer = _pointer + POINT_SIZE; } /** * @notice Read 1 byte from memory in the pointer position */ function getByte(uint256 _pointer) internal pure returns (byte result) { bytes32 word; assembly { word := mload(_pointer) } result = word[0]; return result; } /** * @notice Read 32 bytes from memory in the pointer position */ function getBytes32(uint256 _pointer) internal pure returns (bytes32 result) { assembly { result := mload(_pointer) } } /** * @notice Copy bytes from the source pointer to the target array * @dev Assumes that enough memory has been allocated to store in target. * Also assumes that '_target' was the last thing that was allocated * @param _bytesPointer Source memory pointer * @param _target Target array * @param _bytesLength Number of bytes to copy */ function copyBytes(uint256 _bytesPointer, bytes memory _target, uint256 _bytesLength) internal pure returns (uint256 resultPointer) { // Exploiting the fact that '_target' was the last thing to be allocated, // we can write entire words, and just overwrite any excess. assembly { // evm operations on words let words := div(add(_bytesLength, 31), 32) let source := _bytesPointer let destination := add(_target, 32) for { let i := 0 } // start at arr + 32 -> first byte corresponds to length lt(i, words) { i := add(i, 1) } { let offset := mul(i, 32) mstore(add(destination, offset), mload(add(source, offset))) } mstore(add(_target, add(32, mload(_target))), 0) } resultPointer = _bytesPointer + _bytesLength; } } abstract contract Upgradeable is Ownable { event StateVerified(address indexed testTarget, address sender); event UpgradeFinished(address indexed target, address sender); /** * @dev Contracts at the target must reserve the same location in storage for this address as in Dispatcher * Stored data actually lives in the Dispatcher * However the storage layout is specified here in the implementing contracts */ address public target; /** * @dev Previous contract address (if available). Used for rollback */ address public previousTarget; /** * @dev Upgrade status. Explicit `uint8` type is used instead of `bool` to save gas by excluding 0 value */ uint8 public isUpgrade; /** * @dev Guarantees that next slot will be separated from the previous */ uint256 stubSlot; /** * @dev Constants for `isUpgrade` field */ uint8 constant UPGRADE_FALSE = 1; uint8 constant UPGRADE_TRUE = 2; /** * @dev Checks that function executed while upgrading * Recommended to add to `verifyState` and `finishUpgrade` methods */ modifier onlyWhileUpgrading() { require(isUpgrade == UPGRADE_TRUE); _; } /** * @dev Method for verifying storage state. * Should check that new target contract returns right storage value */ function verifyState(address _testTarget) public virtual onlyWhileUpgrading { emit StateVerified(_testTarget, msg.sender); } /** * @dev Copy values from the new target to the current storage * @param _target New target contract address */ function finishUpgrade(address _target) public virtual onlyWhileUpgrading { emit UpgradeFinished(_target, msg.sender); } /** * @dev Base method to get data * @param _target Target to call * @param _selector Method selector * @param _numberOfArguments Number of used arguments * @param _argument1 First method argument * @param _argument2 Second method argument * @return memoryAddress Address in memory where the data is located */ function delegateGetData( address _target, bytes4 _selector, uint8 _numberOfArguments, bytes32 _argument1, bytes32 _argument2 ) internal returns (bytes32 memoryAddress) { assembly { memoryAddress := mload(0x40) mstore(memoryAddress, _selector) if gt(_numberOfArguments, 0) { mstore(add(memoryAddress, 0x04), _argument1) } if gt(_numberOfArguments, 1) { mstore(add(memoryAddress, 0x24), _argument2) } switch delegatecall(gas(), _target, memoryAddress, add(0x04, mul(0x20, _numberOfArguments)), 0, 0) case 0 { revert(memoryAddress, 0) } default { returndatacopy(memoryAddress, 0x0, returndatasize()) } } } /** * @dev Call "getter" without parameters. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 0, 0, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with one parameter. * Result should not exceed 32 bytes */ function delegateGet(address _target, bytes4 _selector, bytes32 _argument) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 1, _argument, 0); assembly { result := mload(memoryAddress) } } /** * @dev Call "getter" with two parameters. * Result should not exceed 32 bytes */ function delegateGet( address _target, bytes4 _selector, bytes32 _argument1, bytes32 _argument2 ) internal returns (uint256 result) { bytes32 memoryAddress = delegateGetData(_target, _selector, 2, _argument1, _argument2); assembly { result := mload(memoryAddress) } } } contract Adjudicator is Upgradeable { using SafeMath for uint256; using UmbralDeserializer for bytes; event CFragEvaluated( bytes32 indexed evaluationHash, address indexed investigator, bool correctness ); event IncorrectCFragVerdict( bytes32 indexed evaluationHash, address indexed worker, address indexed staker ); // used only for upgrading bytes32 constant RESERVED_CAPSULE_AND_CFRAG_BYTES = bytes32(0); address constant RESERVED_ADDRESS = address(0); StakingEscrow public immutable escrow; SignatureVerifier.HashAlgorithm public immutable hashAlgorithm; uint256 public immutable basePenalty; uint256 public immutable penaltyHistoryCoefficient; uint256 public immutable percentagePenaltyCoefficient; uint256 public immutable rewardCoefficient; mapping (address => uint256) public penaltyHistory; mapping (bytes32 => bool) public evaluatedCFrags; /** * @param _escrow Escrow contract * @param _hashAlgorithm Hashing algorithm * @param _basePenalty Base for the penalty calculation * @param _penaltyHistoryCoefficient Coefficient for calculating the penalty depending on the history * @param _percentagePenaltyCoefficient Coefficient for calculating the percentage penalty * @param _rewardCoefficient Coefficient for calculating the reward */ constructor( StakingEscrow _escrow, SignatureVerifier.HashAlgorithm _hashAlgorithm, uint256 _basePenalty, uint256 _penaltyHistoryCoefficient, uint256 _percentagePenaltyCoefficient, uint256 _rewardCoefficient ) { // Sanity checks. require(_escrow.secondsPerPeriod() > 0 && // This contract has an escrow, and it's not the null address. // The reward and penalty coefficients are set. _percentagePenaltyCoefficient != 0 && _rewardCoefficient != 0); escrow = _escrow; hashAlgorithm = _hashAlgorithm; basePenalty = _basePenalty; percentagePenaltyCoefficient = _percentagePenaltyCoefficient; penaltyHistoryCoefficient = _penaltyHistoryCoefficient; rewardCoefficient = _rewardCoefficient; } /** * @notice Submit proof that a worker created wrong CFrag * @param _capsuleBytes Serialized capsule * @param _cFragBytes Serialized CFrag * @param _cFragSignature Signature of CFrag by worker * @param _taskSignature Signature of task specification by Bob * @param _requesterPublicKey Bob's signing public key, also known as "stamp" * @param _workerPublicKey Worker's signing public key, also known as "stamp" * @param _workerIdentityEvidence Signature of worker's public key by worker's eth-key * @param _preComputedData Additional pre-computed data for CFrag correctness verification */ function evaluateCFrag( bytes memory _capsuleBytes, bytes memory _cFragBytes, bytes memory _cFragSignature, bytes memory _taskSignature, bytes memory _requesterPublicKey, bytes memory _workerPublicKey, bytes memory _workerIdentityEvidence, bytes memory _preComputedData ) public { // 1. Check that CFrag is not evaluated yet bytes32 evaluationHash = SignatureVerifier.hash( abi.encodePacked(_capsuleBytes, _cFragBytes), hashAlgorithm); require(!evaluatedCFrags[evaluationHash], "This CFrag has already been evaluated."); evaluatedCFrags[evaluationHash] = true; // 2. Verify correctness of re-encryption bool cFragIsCorrect = ReEncryptionValidator.validateCFrag(_capsuleBytes, _cFragBytes, _preComputedData); emit CFragEvaluated(evaluationHash, msg.sender, cFragIsCorrect); // 3. Verify associated public keys and signatures require(ReEncryptionValidator.checkSerializedCoordinates(_workerPublicKey), "Staker's public key is invalid"); require(ReEncryptionValidator.checkSerializedCoordinates(_requesterPublicKey), "Requester's public key is invalid"); UmbralDeserializer.PreComputedData memory precomp = _preComputedData.toPreComputedData(); // Verify worker's signature of CFrag require(SignatureVerifier.verify( _cFragBytes, abi.encodePacked(_cFragSignature, precomp.lostBytes[1]), _workerPublicKey, hashAlgorithm), "CFrag signature is invalid" ); // Verify worker's signature of taskSignature and that it corresponds to cfrag.proof.metadata UmbralDeserializer.CapsuleFrag memory cFrag = _cFragBytes.toCapsuleFrag(); require(SignatureVerifier.verify( _taskSignature, abi.encodePacked(cFrag.proof.metadata, precomp.lostBytes[2]), _workerPublicKey, hashAlgorithm), "Task signature is invalid" ); // Verify that _taskSignature is bob's signature of the task specification. // A task specification is: capsule + ursula pubkey + alice address + blockhash bytes32 stampXCoord; assembly { stampXCoord := mload(add(_workerPublicKey, 32)) } bytes memory stamp = abi.encodePacked(precomp.lostBytes[4], stampXCoord); require(SignatureVerifier.verify( abi.encodePacked(_capsuleBytes, stamp, _workerIdentityEvidence, precomp.alicesKeyAsAddress, bytes32(0)), abi.encodePacked(_taskSignature, precomp.lostBytes[3]), _requesterPublicKey, hashAlgorithm), "Specification signature is invalid" ); // 4. Extract worker address from stamp signature. address worker = SignatureVerifier.recover( SignatureVerifier.hashEIP191(stamp, byte(0x45)), // Currently, we use version E (0x45) of EIP191 signatures _workerIdentityEvidence); address staker = escrow.stakerFromWorker(worker); require(staker != address(0), "Worker must be related to a staker"); // 5. Check that staker can be slashed uint256 stakerValue = escrow.getAllTokens(staker); require(stakerValue > 0, "Staker has no tokens"); // 6. If CFrag was incorrect, slash staker if (!cFragIsCorrect) { (uint256 penalty, uint256 reward) = calculatePenaltyAndReward(staker, stakerValue); escrow.slashStaker(staker, penalty, msg.sender, reward); emit IncorrectCFragVerdict(evaluationHash, worker, staker); } } /** * @notice Calculate penalty to the staker and reward to the investigator * @param _staker Staker's address * @param _stakerValue Amount of tokens that belong to the staker */ function calculatePenaltyAndReward(address _staker, uint256 _stakerValue) internal returns (uint256 penalty, uint256 reward) { penalty = basePenalty.add(penaltyHistoryCoefficient.mul(penaltyHistory[_staker])); penalty = Math.min(penalty, _stakerValue.div(percentagePenaltyCoefficient)); reward = penalty.div(rewardCoefficient); // TODO add maximum condition or other overflow protection or other penalty condition (#305?) penaltyHistory[_staker] = penaltyHistory[_staker].add(1); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); require(delegateGet(_testTarget, this.evaluatedCFrags.selector, evaluationCFragHash) == (evaluatedCFrags[evaluationCFragHash] ? 1 : 0)); require(delegateGet(_testTarget, this.penaltyHistory.selector, bytes32(bytes20(RESERVED_ADDRESS))) == penaltyHistory[RESERVED_ADDRESS]); } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // preparation for the verifyState method bytes32 evaluationCFragHash = SignatureVerifier.hash( abi.encodePacked(RESERVED_CAPSULE_AND_CFRAG_BYTES), SignatureVerifier.HashAlgorithm.SHA256); evaluatedCFrags[evaluationCFragHash] = true; penaltyHistory[RESERVED_ADDRESS] = 123; } } contract Dispatcher is Upgradeable, ERCProxy { using Address for address; event Upgraded(address indexed from, address indexed to, address owner); event RolledBack(address indexed from, address indexed to, address owner); /** * @dev Set upgrading status before and after operations */ modifier upgrading() { isUpgrade = UPGRADE_TRUE; _; isUpgrade = UPGRADE_FALSE; } /** * @param _target Target contract address */ constructor(address _target) upgrading { require(_target.isContract()); // Checks that target contract inherits Dispatcher state verifyState(_target); // `verifyState` must work with its contract verifyUpgradeableState(_target, _target); target = _target; finishUpgrade(); emit Upgraded(address(0), _target, msg.sender); } //------------------------ERC897------------------------ /** * @notice ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() external pure override returns (uint256) { return 2; } /** * @notice ERC897, gets the address of the implementation where every call will be delegated */ function implementation() external view override returns (address) { return target; } //------------------------------------------------------------ /** * @notice Verify new contract storage and upgrade target * @param _target New target contract address */ function upgrade(address _target) public onlyOwner upgrading { require(_target.isContract()); // Checks that target contract has "correct" (as much as possible) state layout verifyState(_target); //`verifyState` must work with its contract verifyUpgradeableState(_target, _target); if (target.isContract()) { verifyUpgradeableState(target, _target); } previousTarget = target; target = _target; finishUpgrade(); emit Upgraded(previousTarget, _target, msg.sender); } /** * @notice Rollback to previous target * @dev Test storage carefully before upgrade again after rollback */ function rollback() public onlyOwner upgrading { require(previousTarget.isContract()); emit RolledBack(target, previousTarget, msg.sender); // should be always true because layout previousTarget -> target was already checked // but `verifyState` is not 100% accurate so check again verifyState(previousTarget); if (target.isContract()) { verifyUpgradeableState(previousTarget, target); } target = previousTarget; previousTarget = address(0); finishUpgrade(); } /** * @dev Call verifyState method for Upgradeable contract */ function verifyUpgradeableState(address _from, address _to) private { (bool callSuccess,) = _from.delegatecall(abi.encodeWithSelector(this.verifyState.selector, _to)); require(callSuccess); } /** * @dev Call finishUpgrade method from the Upgradeable contract */ function finishUpgrade() private { (bool callSuccess,) = target.delegatecall(abi.encodeWithSelector(this.finishUpgrade.selector, target)); require(callSuccess); } function verifyState(address _testTarget) public override onlyWhileUpgrading { //checks equivalence accessing state through new contract and current storage require(address(uint160(delegateGet(_testTarget, this.owner.selector))) == owner()); require(address(uint160(delegateGet(_testTarget, this.target.selector))) == target); require(address(uint160(delegateGet(_testTarget, this.previousTarget.selector))) == previousTarget); require(uint8(delegateGet(_testTarget, this.isUpgrade.selector)) == isUpgrade); } /** * @dev Override function using empty code because no reason to call this function in Dispatcher */ function finishUpgrade(address) public override {} /** * @dev Receive function sends empty request to the target contract */ receive() external payable { assert(target.isContract()); // execute receive function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(""); if (!callSuccess) { revert(); } } /** * @dev Fallback function sends all requests to the target contract */ fallback() external payable { assert(target.isContract()); // execute requested function from target contract using storage of the dispatcher (bool callSuccess,) = target.delegatecall(msg.data); if (callSuccess) { // copy result of the request to the return data // we can use the second return value from `delegatecall` (bytes memory) // but it will consume a little more gas assembly { returndatacopy(0x0, 0x0, returndatasize()) return(0x0, returndatasize()) } } else { revert(); } } } abstract contract Issuer is Upgradeable { using SafeERC20 for NuCypherToken; using AdditionalMath for uint32; event Donated(address indexed sender, uint256 value); /// Issuer is initialized with a reserved reward event Initialized(uint256 reservedReward); uint128 constant MAX_UINT128 = uint128(0) - 1; NuCypherToken public immutable token; uint128 public immutable totalSupply; // d * k2 uint256 public immutable mintingCoefficient; // k1 uint256 public immutable lockDurationCoefficient1; // k2 uint256 public immutable lockDurationCoefficient2; uint32 public immutable secondsPerPeriod; // kmax uint16 public immutable maximumRewardedPeriods; uint256 public immutable firstPhaseMaxIssuance; uint256 public immutable firstPhaseTotalSupply; /** * Current supply is used in the minting formula and is stored to prevent different calculation * for stakers which get reward in the same period. There are two values - * supply for previous period (used in formula) and supply for current period which accumulates value * before end of period. */ uint128 public previousPeriodSupply; uint128 public currentPeriodSupply; uint16 public currentMintingPeriod; /** * @notice Constructor sets address of token contract and coefficients for minting * @dev Minting formula for one sub-stake in one period for the first phase firstPhaseMaxIssuance * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 * @dev Minting formula for one sub-stake in one period for the second phase (totalSupply - currentSupply) / d * (lockedValue / totalLockedValue) * (k1 + min(allLockedPeriods, kmax)) / k2 if allLockedPeriods > maximumRewardedPeriods then allLockedPeriods = maximumRewardedPeriods * @param _token Token contract * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. */ constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance ) { uint256 localTotalSupply = _token.totalSupply(); require(localTotalSupply > 0 && _issuanceDecayCoefficient != 0 && _hoursPerPeriod != 0 && _lockDurationCoefficient1 != 0 && _lockDurationCoefficient2 != 0 && _maximumRewardedPeriods != 0); require(localTotalSupply <= uint256(MAX_UINT128), "Token contract has supply more than supported"); uint256 maxLockDurationCoefficient = _maximumRewardedPeriods + _lockDurationCoefficient1; uint256 localMintingCoefficient = _issuanceDecayCoefficient * _lockDurationCoefficient2; require(maxLockDurationCoefficient > _maximumRewardedPeriods && localMintingCoefficient / _issuanceDecayCoefficient == _lockDurationCoefficient2 && // worst case for `totalLockedValue * d * k2`, when totalLockedValue == totalSupply localTotalSupply * localMintingCoefficient / localTotalSupply == localMintingCoefficient && // worst case for `(totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax))`, // when currentSupply == 0, lockedValue == totalSupply localTotalSupply * localTotalSupply * maxLockDurationCoefficient / localTotalSupply / localTotalSupply == maxLockDurationCoefficient, "Specified parameters cause overflow"); require(maxLockDurationCoefficient <= _lockDurationCoefficient2, "Resulting locking duration coefficient must be less than 1"); require(_firstPhaseTotalSupply <= localTotalSupply, "Too many tokens for the first phase"); require(_firstPhaseMaxIssuance <= _firstPhaseTotalSupply, "Reward for the first phase is too high"); token = _token; secondsPerPeriod = _hoursPerPeriod.mul32(1 hours); lockDurationCoefficient1 = _lockDurationCoefficient1; lockDurationCoefficient2 = _lockDurationCoefficient2; maximumRewardedPeriods = _maximumRewardedPeriods; firstPhaseTotalSupply = _firstPhaseTotalSupply; firstPhaseMaxIssuance = _firstPhaseMaxIssuance; totalSupply = uint128(localTotalSupply); mintingCoefficient = localMintingCoefficient; } /** * @dev Checks contract initialization */ modifier isInitialized() { require(currentMintingPeriod != 0); _; } /** * @return Number of current period */ function getCurrentPeriod() public view returns (uint16) { return uint16(block.timestamp / secondsPerPeriod); } /** * @notice Initialize reserved tokens for reward */ function initialize(uint256 _reservedReward, address _sourceOfFunds) external onlyOwner { require(currentMintingPeriod == 0); // Reserved reward must be sufficient for at least one period of the first phase require(firstPhaseMaxIssuance <= _reservedReward); currentMintingPeriod = getCurrentPeriod(); currentPeriodSupply = totalSupply - uint128(_reservedReward); previousPeriodSupply = currentPeriodSupply; token.safeTransferFrom(_sourceOfFunds, address(this), _reservedReward); emit Initialized(_reservedReward); } /** * @notice Function to mint tokens for one period. * @param _currentPeriod Current period number. * @param _lockedValue The amount of tokens that were locked by user in specified period. * @param _totalLockedValue The amount of tokens that were locked by all users in specified period. * @param _allLockedPeriods The max amount of periods during which tokens will be locked after specified period. * @return amount Amount of minted tokens. */ function mint( uint16 _currentPeriod, uint256 _lockedValue, uint256 _totalLockedValue, uint16 _allLockedPeriods ) internal returns (uint256 amount) { if (currentPeriodSupply == totalSupply) { return 0; } if (_currentPeriod > currentMintingPeriod) { previousPeriodSupply = currentPeriodSupply; currentMintingPeriod = _currentPeriod; } uint256 currentReward; uint256 coefficient; // first phase // firstPhaseMaxIssuance * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * k2) if (previousPeriodSupply + firstPhaseMaxIssuance <= firstPhaseTotalSupply) { currentReward = firstPhaseMaxIssuance; coefficient = lockDurationCoefficient2; // second phase // (totalSupply - currentSupply) * lockedValue * (k1 + min(allLockedPeriods, kmax)) / (totalLockedValue * d * k2) } else { currentReward = totalSupply - previousPeriodSupply; coefficient = mintingCoefficient; } uint256 allLockedPeriods = AdditionalMath.min16(_allLockedPeriods, maximumRewardedPeriods) + lockDurationCoefficient1; amount = (uint256(currentReward) * _lockedValue * allLockedPeriods) / (_totalLockedValue * coefficient); // rounding the last reward uint256 maxReward = getReservedReward(); if (amount == 0) { amount = 1; } else if (amount > maxReward) { amount = maxReward; } currentPeriodSupply += uint128(amount); } /** * @notice Return tokens for future minting * @param _amount Amount of tokens */ function unMint(uint256 _amount) internal { previousPeriodSupply -= uint128(_amount); currentPeriodSupply -= uint128(_amount); } /** * @notice Donate sender's tokens. Amount of tokens will be returned for future minting * @param _value Amount to donate */ function donate(uint256 _value) external isInitialized { token.safeTransferFrom(msg.sender, address(this), _value); unMint(_value); emit Donated(msg.sender, _value); } /** * @notice Returns the number of tokens that can be minted */ function getReservedReward() public view returns (uint256) { return totalSupply - currentPeriodSupply; } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(uint16(delegateGet(_testTarget, this.currentMintingPeriod.selector)) == currentMintingPeriod); require(uint128(delegateGet(_testTarget, this.previousPeriodSupply.selector)) == previousPeriodSupply); require(uint128(delegateGet(_testTarget, this.currentPeriodSupply.selector)) == currentPeriodSupply); } } contract StakingEscrow is Issuer, IERC900History { using AdditionalMath for uint256; using AdditionalMath for uint16; using Bits for uint256; using SafeMath for uint256; using Snapshot for uint128[]; using SafeERC20 for NuCypherToken; event Deposited(address indexed staker, uint256 value, uint16 periods); event Locked(address indexed staker, uint256 value, uint16 firstPeriod, uint16 periods); event Divided( address indexed staker, uint256 oldValue, uint16 lastPeriod, uint256 newValue, uint16 periods ); event Merged(address indexed staker, uint256 value1, uint256 value2, uint16 lastPeriod); event Prolonged(address indexed staker, uint256 value, uint16 lastPeriod, uint16 periods); event Withdrawn(address indexed staker, uint256 value); event CommitmentMade(address indexed staker, uint16 indexed period, uint256 value); event Minted(address indexed staker, uint16 indexed period, uint256 value); event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward); event ReStakeSet(address indexed staker, bool reStake); event ReStakeLocked(address indexed staker, uint16 lockUntilPeriod); event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod); event WorkMeasurementSet(address indexed staker, bool measureWork); event WindDownSet(address indexed staker, bool windDown); event SnapshotSet(address indexed staker, bool snapshotsEnabled); struct SubStakeInfo { uint16 firstPeriod; uint16 lastPeriod; uint16 periods; uint128 lockedValue; } struct Downtime { uint16 startPeriod; uint16 endPeriod; } struct StakerInfo { uint256 value; /* * Stores periods that are committed but not yet rewarded. * In order to optimize storage, only two values are used instead of an array. * commitToNextPeriod() method invokes mint() method so there can only be two committed * periods that are not yet rewarded: the current and the next periods. */ uint16 currentCommittedPeriod; uint16 nextCommittedPeriod; uint16 lastCommittedPeriod; uint16 lockReStakeUntilPeriod; uint256 completedWork; uint16 workerStartPeriod; // period when worker was bonded address worker; uint256 flags; // uint256 to acquire whole slot and minimize operations on it uint256 reservedSlot1; uint256 reservedSlot2; uint256 reservedSlot3; uint256 reservedSlot4; uint256 reservedSlot5; Downtime[] pastDowntime; SubStakeInfo[] subStakes; uint128[] history; } // used only for upgrading uint16 internal constant RESERVED_PERIOD = 0; uint16 internal constant MAX_CHECKED_VALUES = 5; // to prevent high gas consumption in loops for slashing uint16 public constant MAX_SUB_STAKES = 30; uint16 internal constant MAX_UINT16 = 65535; // indices for flags uint8 internal constant RE_STAKE_DISABLED_INDEX = 0; uint8 internal constant WIND_DOWN_INDEX = 1; uint8 internal constant MEASURE_WORK_INDEX = 2; uint8 internal constant SNAPSHOTS_DISABLED_INDEX = 3; uint16 public immutable minLockedPeriods; uint16 public immutable minWorkerPeriods; uint256 public immutable minAllowableLockedTokens; uint256 public immutable maxAllowableLockedTokens; bool public immutable isTestContract; mapping (address => StakerInfo) public stakerInfo; address[] public stakers; mapping (address => address) public stakerFromWorker; mapping (uint16 => uint256) public lockedPerPeriod; uint128[] public balanceHistory; PolicyManagerInterface public policyManager; AdjudicatorInterface public adjudicator; WorkLockInterface public workLock; /** * @notice Constructor sets address of token contract and coefficients for minting * @param _token Token contract * @param _hoursPerPeriod Size of period in hours * @param _issuanceDecayCoefficient (d) Coefficient which modifies the rate at which the maximum issuance decays, * only applicable to Phase 2. d = 365 * half-life / LOG2 where default half-life = 2. * See Equation 10 in Staking Protocol & Economics paper * @param _lockDurationCoefficient1 (k1) Numerator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k1 = k2 * small_stake_multiplier where default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _lockDurationCoefficient2 (k2) Denominator of the coefficient which modifies the extent * to which a stake's lock duration affects the subsidy it receives. Affects stakers differently. * Applicable to Phase 1 and Phase 2. k2 = maximum_rewarded_periods / (1 - small_stake_multiplier) * where default maximum_rewarded_periods = 365 and default small_stake_multiplier = 0.5. * See Equation 8 in Staking Protocol & Economics paper. * @param _maximumRewardedPeriods (kmax) Number of periods beyond which a stake's lock duration * no longer increases the subsidy it receives. kmax = reward_saturation * 365 where default reward_saturation = 1. * See Equation 8 in Staking Protocol & Economics paper. * @param _firstPhaseTotalSupply Total supply for the first phase * @param _firstPhaseMaxIssuance (Imax) Maximum number of new tokens minted per period during Phase 1. * See Equation 7 in Staking Protocol & Economics paper. * @param _minLockedPeriods Min amount of periods during which tokens can be locked * @param _minAllowableLockedTokens Min amount of tokens that can be locked * @param _maxAllowableLockedTokens Max amount of tokens that can be locked * @param _minWorkerPeriods Min amount of periods while a worker can't be changed * @param _isTestContract True if contract is only for tests */ constructor( NuCypherToken _token, uint32 _hoursPerPeriod, uint256 _issuanceDecayCoefficient, uint256 _lockDurationCoefficient1, uint256 _lockDurationCoefficient2, uint16 _maximumRewardedPeriods, uint256 _firstPhaseTotalSupply, uint256 _firstPhaseMaxIssuance, uint16 _minLockedPeriods, uint256 _minAllowableLockedTokens, uint256 _maxAllowableLockedTokens, uint16 _minWorkerPeriods, bool _isTestContract ) Issuer( _token, _hoursPerPeriod, _issuanceDecayCoefficient, _lockDurationCoefficient1, _lockDurationCoefficient2, _maximumRewardedPeriods, _firstPhaseTotalSupply, _firstPhaseMaxIssuance ) { // constant `1` in the expression `_minLockedPeriods > 1` uses to simplify the `lock` method require(_minLockedPeriods > 1 && _maxAllowableLockedTokens != 0); minLockedPeriods = _minLockedPeriods; minAllowableLockedTokens = _minAllowableLockedTokens; maxAllowableLockedTokens = _maxAllowableLockedTokens; minWorkerPeriods = _minWorkerPeriods; isTestContract = _isTestContract; } /** * @dev Checks the existence of a staker in the contract */ modifier onlyStaker() { StakerInfo storage info = stakerInfo[msg.sender]; require(info.value > 0 || info.nextCommittedPeriod != 0); _; } //------------------------Initialization------------------------ /** * @notice Set policy manager address */ function setPolicyManager(PolicyManagerInterface _policyManager) external onlyOwner { // Policy manager can be set only once require(address(policyManager) == address(0)); // This escrow must be the escrow for the new policy manager require(_policyManager.escrow() == address(this)); policyManager = _policyManager; } /** * @notice Set adjudicator address */ function setAdjudicator(AdjudicatorInterface _adjudicator) external onlyOwner { // Adjudicator can be set only once require(address(adjudicator) == address(0)); // This escrow must be the escrow for the new adjudicator require(_adjudicator.escrow() == address(this)); adjudicator = _adjudicator; } /** * @notice Set worklock address */ function setWorkLock(WorkLockInterface _workLock) external onlyOwner { // WorkLock can be set only once require(address(workLock) == address(0) || isTestContract); // This escrow must be the escrow for the new worklock require(_workLock.escrow() == address(this)); workLock = _workLock; } //------------------------Main getters------------------------ /** * @notice Get all tokens belonging to the staker */ function getAllTokens(address _staker) external view returns (uint256) { return stakerInfo[_staker].value; } /** * @notice Get all flags for the staker */ function getFlags(address _staker) external view returns ( bool windDown, bool reStake, bool measureWork, bool snapshots ) { StakerInfo storage info = stakerInfo[_staker]; windDown = info.flags.bitSet(WIND_DOWN_INDEX); reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); measureWork = info.flags.bitSet(MEASURE_WORK_INDEX); snapshots = !info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX); } /** * @notice Get the start period. Use in the calculation of the last period of the sub stake * @param _info Staker structure * @param _currentPeriod Current period */ function getStartPeriod(StakerInfo storage _info, uint16 _currentPeriod) internal view returns (uint16) { // if the next period (after current) is committed if (_info.flags.bitSet(WIND_DOWN_INDEX) && _info.nextCommittedPeriod > _currentPeriod) { return _currentPeriod + 1; } return _currentPeriod; } /** * @notice Get the last period of the sub stake * @param _subStake Sub stake structure * @param _startPeriod Pre-calculated start period */ function getLastPeriodOfSubStake(SubStakeInfo storage _subStake, uint16 _startPeriod) internal view returns (uint16) { if (_subStake.lastPeriod != 0) { return _subStake.lastPeriod; } uint32 lastPeriod = uint32(_startPeriod) + _subStake.periods; if (lastPeriod > uint32(MAX_UINT16)) { return MAX_UINT16; } return uint16(lastPeriod); } /** * @notice Get the last period of the sub stake * @param _staker Staker * @param _index Stake index */ function getLastPeriodOfSubStake(address _staker, uint256 _index) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; SubStakeInfo storage subStake = info.subStakes[_index]; uint16 startPeriod = getStartPeriod(info, getCurrentPeriod()); return getLastPeriodOfSubStake(subStake, startPeriod); } /** * @notice Get the value of locked tokens for a staker in a specified period * @dev Information may be incorrect for rewarded or not committed surpassed period * @param _info Staker structure * @param _currentPeriod Current period * @param _period Next period */ function getLockedTokens(StakerInfo storage _info, uint16 _currentPeriod, uint16 _period) internal view returns (uint256 lockedValue) { lockedValue = 0; uint16 startPeriod = getStartPeriod(_info, _currentPeriod); for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.firstPeriod <= _period && getLastPeriodOfSubStake(subStake, startPeriod) >= _period) { lockedValue += subStake.lockedValue; } } } /** * @notice Get the value of locked tokens for a staker in a future period * @dev This function is used by PreallocationEscrow so its signature can't be updated. * @param _staker Staker * @param _periods Amount of periods that will be added to the current period */ function getLockedTokens(address _staker, uint16 _periods) external view returns (uint256 lockedValue) { StakerInfo storage info = stakerInfo[_staker]; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_periods); return getLockedTokens(info, currentPeriod, nextPeriod); } /** * @notice Get the last committed staker's period * @param _staker Staker */ function getLastCommittedPeriod(address _staker) public view returns (uint16) { StakerInfo storage info = stakerInfo[_staker]; return info.nextCommittedPeriod != 0 ? info.nextCommittedPeriod : info.lastCommittedPeriod; } /** * @notice Get the value of locked tokens for active stakers in (getCurrentPeriod() + _periods) period * as well as stakers and their locked tokens * @param _periods Amount of periods for locked tokens calculation * @param _startIndex Start index for looking in stakers array * @param _maxStakers Max stakers for looking, if set 0 then all will be used * @return allLockedTokens Sum of locked tokens for active stakers * @return activeStakers Array of stakers and their locked tokens. Stakers addresses stored as uint256 * @dev Note that activeStakers[0] in an array of uint256, but you want addresses. Careful when used directly! */ function getActiveStakers(uint16 _periods, uint256 _startIndex, uint256 _maxStakers) external view returns (uint256 allLockedTokens, uint256[2][] memory activeStakers) { require(_periods > 0); uint256 endIndex = stakers.length; require(_startIndex < endIndex); if (_maxStakers != 0 && _startIndex + _maxStakers < endIndex) { endIndex = _startIndex + _maxStakers; } activeStakers = new uint256[2][](endIndex - _startIndex); allLockedTokens = 0; uint256 resultIndex = 0; uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod.add16(_periods); for (uint256 i = _startIndex; i < endIndex; i++) { address staker = stakers[i]; StakerInfo storage info = stakerInfo[staker]; if (info.currentCommittedPeriod != currentPeriod && info.nextCommittedPeriod != currentPeriod) { continue; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); if (lockedTokens != 0) { activeStakers[resultIndex][0] = uint256(staker); activeStakers[resultIndex++][1] = lockedTokens; allLockedTokens += lockedTokens; } } assembly { mstore(activeStakers, resultIndex) } } /** * @notice Checks if `reStake` parameter is available for changing * @param _staker Staker */ function isReStakeLocked(address _staker) public view returns (bool) { return getCurrentPeriod() < stakerInfo[_staker].lockReStakeUntilPeriod; } /** * @notice Get worker using staker's address */ function getWorkerFromStaker(address _staker) external view returns (address) { return stakerInfo[_staker].worker; } /** * @notice Get work that completed by the staker */ function getCompletedWork(address _staker) external view returns (uint256) { return stakerInfo[_staker].completedWork; } /** * @notice Find index of downtime structure that includes specified period * @dev If specified period is outside all downtime periods, the length of the array will be returned * @param _staker Staker * @param _period Specified period number */ function findIndexOfPastDowntime(address _staker, uint16 _period) external view returns (uint256 index) { StakerInfo storage info = stakerInfo[_staker]; for (index = 0; index < info.pastDowntime.length; index++) { if (_period <= info.pastDowntime[index].endPeriod) { return index; } } } //------------------------Main methods------------------------ /** * @notice Start or stop measuring the work of a staker * @param _staker Staker * @param _measureWork Value for `measureWork` parameter * @return Work that was previously done */ function setWorkMeasurement(address _staker, bool _measureWork) external returns (uint256) { require(msg.sender == address(workLock)); StakerInfo storage info = stakerInfo[_staker]; if (info.flags.bitSet(MEASURE_WORK_INDEX) == _measureWork) { return info.completedWork; } info.flags = info.flags.toggleBit(MEASURE_WORK_INDEX); emit WorkMeasurementSet(_staker, _measureWork); return info.completedWork; } /** * @notice Bond worker * @param _worker Worker address. Must be a real address, not a contract */ function bondWorker(address _worker) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Specified worker is already bonded with this staker require(_worker != info.worker); uint16 currentPeriod = getCurrentPeriod(); if (info.worker != address(0)) { // If this staker had a worker ... // Check that enough time has passed to change it require(currentPeriod >= info.workerStartPeriod.add16(minWorkerPeriods)); // Remove the old relation "worker->staker" stakerFromWorker[info.worker] = address(0); } if (_worker != address(0)) { // Specified worker is already in use require(stakerFromWorker[_worker] == address(0)); // Specified worker is a staker require(stakerInfo[_worker].subStakes.length == 0 || _worker == msg.sender); // Set new worker->staker relation stakerFromWorker[_worker] = msg.sender; } // Bond new worker (or unbond if _worker == address(0)) info.worker = _worker; info.workerStartPeriod = currentPeriod; emit WorkerBonded(msg.sender, _worker, currentPeriod); } /** * @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake * Only if this parameter is not locked * @param _reStake Value for parameter */ function setReStake(bool _reStake) external { require(!isReStakeLocked(msg.sender)); StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) { return; } info.flags = info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(msg.sender, _reStake); } /** * @notice Lock `reStake` parameter. Only if this parameter is not locked * @param _lockReStakeUntilPeriod Can't change `reStake` value until this period */ function lockReStake(uint16 _lockReStakeUntilPeriod) external { require(!isReStakeLocked(msg.sender) && _lockReStakeUntilPeriod > getCurrentPeriod()); stakerInfo[msg.sender].lockReStakeUntilPeriod = _lockReStakeUntilPeriod; emit ReStakeLocked(msg.sender, _lockReStakeUntilPeriod); } /** * @notice Enable `reStake` and lock this parameter even if parameter is locked * @param _staker Staker address * @param _info Staker structure * @param _lockReStakeUntilPeriod Can't change `reStake` value until this period */ function forceLockReStake( address _staker, StakerInfo storage _info, uint16 _lockReStakeUntilPeriod ) internal { // reset bit when `reStake` is already disabled if (_info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == true) { _info.flags = _info.flags.toggleBit(RE_STAKE_DISABLED_INDEX); emit ReStakeSet(_staker, true); } // lock `reStake` parameter if it's not locked or locked for too short duration if (_lockReStakeUntilPeriod > _info.lockReStakeUntilPeriod) { _info.lockReStakeUntilPeriod = _lockReStakeUntilPeriod; emit ReStakeLocked(_staker, _lockReStakeUntilPeriod); } } /** * @notice Deposit tokens and lock `reStake` parameter from WorkLock contract * @param _staker Staker address * @param _value Amount of tokens to deposit * @param _periods Amount of periods during which tokens will be locked * and number of period after which `reStake` can be changed */ function depositFromWorkLock( address _staker, uint256 _value, uint16 _periods ) external { require(msg.sender == address(workLock)); deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _periods); StakerInfo storage info = stakerInfo[_staker]; uint16 lockReStakeUntilPeriod = getCurrentPeriod().add16(_periods).add16(1); forceLockReStake(_staker, info, lockReStakeUntilPeriod); } /** * @notice Set `windDown` parameter. * If true then stake's duration will be decreasing in each period with `commitToNextPeriod()` * @param _windDown Value for parameter */ function setWindDown(bool _windDown) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(WIND_DOWN_INDEX) == _windDown) { return; } info.flags = info.flags.toggleBit(WIND_DOWN_INDEX); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; emit WindDownSet(msg.sender, _windDown); // duration adjustment if next period is committed if (info.nextCommittedPeriod != nextPeriod) { return; } // adjust sub-stakes duration for the new value of winding down parameter for (uint256 index = 0; index < info.subStakes.length; index++) { SubStakeInfo storage subStake = info.subStakes[index]; // sub-stake does not have fixed last period when winding down is disabled if (!_windDown && subStake.lastPeriod == nextPeriod) { subStake.lastPeriod = 0; subStake.periods = 1; continue; } // this sub-stake is no longer affected by winding down parameter if (subStake.lastPeriod != 0 || subStake.periods == 0) { continue; } subStake.periods = _windDown ? subStake.periods - 1 : subStake.periods + 1; if (subStake.periods == 0) { subStake.lastPeriod = nextPeriod; } } } /** * @notice Activate/deactivate taking snapshots of balances * @param _enableSnapshots True to activate snapshots, False to deactivate */ function setSnapshots(bool _enableSnapshots) external { StakerInfo storage info = stakerInfo[msg.sender]; if (info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX) == !_enableSnapshots) { return; } uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); if(_enableSnapshots){ info.history.addSnapshot(info.value); balanceHistory.addSnapshot(lastGlobalBalance + info.value); } else { info.history.addSnapshot(0); balanceHistory.addSnapshot(lastGlobalBalance - info.value); } info.flags = info.flags.toggleBit(SNAPSHOTS_DISABLED_INDEX); emit SnapshotSet(msg.sender, _enableSnapshots); } /** * @notice Adds a new snapshot to both the staker and global balance histories, * assuming the staker's balance was already changed * @param _info Reference to affected staker's struct * @param _addition Variance in balance. It can be positive or negative. */ function addSnapshot(StakerInfo storage _info, int256 _addition) internal { if(!_info.flags.bitSet(SNAPSHOTS_DISABLED_INDEX)){ _info.history.addSnapshot(_info.value); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance.addSigned(_addition)); } } /** * @notice Batch deposit. Allowed only initial deposit for each staker * @param _stakers Stakers * @param _numberOfSubStakes Number of sub-stakes which belong to staker in _values and _periods arrays * @param _values Amount of tokens to deposit for each staker * @param _periods Amount of periods during which tokens will be locked for each staker * @param _lockReStakeUntilPeriod Can't change `reStake` value until this period. Zero value will disable locking */ function batchDeposit( address[] calldata _stakers, uint256[] calldata _numberOfSubStakes, uint256[] calldata _values, uint16[] calldata _periods, uint16 _lockReStakeUntilPeriod ) // `onlyOwner` modifier is for prevent malicious using of `forceLockReStake` // remove `onlyOwner` if `forceLockReStake` will be removed external onlyOwner { uint256 subStakesLength = _values.length; require(_stakers.length != 0 && _stakers.length == _numberOfSubStakes.length && subStakesLength >= _stakers.length && _periods.length == subStakesLength); uint16 previousPeriod = getCurrentPeriod() - 1; uint16 nextPeriod = previousPeriod + 2; uint256 sumValue = 0; uint256 j = 0; for (uint256 i = 0; i < _stakers.length; i++) { address staker = _stakers[i]; uint256 numberOfSubStakes = _numberOfSubStakes[i]; uint256 endIndex = j + numberOfSubStakes; require(numberOfSubStakes > 0 && subStakesLength >= endIndex); StakerInfo storage info = stakerInfo[staker]; require(info.subStakes.length == 0); // A staker can't be a worker for another staker require(stakerFromWorker[staker] == address(0)); stakers.push(staker); policyManager.register(staker, previousPeriod); for (; j < endIndex; j++) { uint256 value = _values[j]; uint16 periods = _periods[j]; require(value >= minAllowableLockedTokens && periods >= minLockedPeriods); info.value = info.value.add(value); info.subStakes.push(SubStakeInfo(nextPeriod, 0, periods, uint128(value))); sumValue = sumValue.add(value); emit Deposited(staker, value, periods); emit Locked(staker, value, nextPeriod, periods); } require(info.value <= maxAllowableLockedTokens); info.history.addSnapshot(info.value); if (_lockReStakeUntilPeriod >= nextPeriod) { forceLockReStake(staker, info, _lockReStakeUntilPeriod); } } require(j == subStakesLength); uint256 lastGlobalBalance = uint256(balanceHistory.lastValue()); balanceHistory.addSnapshot(lastGlobalBalance + sumValue); token.safeTransferFrom(msg.sender, address(this), sumValue); } /** * @notice Implementation of the receiveApproval(address,uint256,address,bytes) method * (see NuCypherToken contract). Deposit all tokens that were approved to transfer * @param _from Staker * @param _value Amount of tokens to deposit * @param _tokenContract Token contract address * @notice (param _extraData) Amount of periods during which tokens will be locked */ function receiveApproval( address _from, uint256 _value, address _tokenContract, bytes calldata /* _extraData */ ) external { require(_tokenContract == address(token) && msg.sender == address(token)); // Copy first 32 bytes from _extraData, according to calldata memory layout: // // 0x00: method signature 4 bytes // 0x04: _from 32 bytes after encoding // 0x24: _value 32 bytes after encoding // 0x44: _tokenContract 32 bytes after encoding // 0x64: _extraData pointer 32 bytes. Value must be 0x80 (offset of _extraData wrt to 1st parameter) // 0x84: _extraData length 32 bytes // 0xA4: _extraData data Length determined by previous variable // // See https://solidity.readthedocs.io/en/latest/abi-spec.html#examples uint256 payloadSize; uint256 payload; assembly { payloadSize := calldataload(0x84) payload := calldataload(0xA4) } payload = payload >> 8*(32 - payloadSize); deposit(_from, _from, MAX_SUB_STAKES, _value, uint16(payload)); } /** * @notice Deposit tokens and create new sub-stake. Use this method to become a staker * @param _staker Staker * @param _value Amount of tokens to deposit * @param _periods Amount of periods during which tokens will be locked */ function deposit(address _staker, uint256 _value, uint16 _periods) external { deposit(_staker, msg.sender, MAX_SUB_STAKES, _value, _periods); } /** * @notice Deposit tokens and increase lock amount of an existing sub-stake * @dev This is preferable way to stake tokens because will be fewer active sub-stakes in the result * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked */ function depositAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); deposit(msg.sender, msg.sender, _index, _value, 0); } /** * @notice Deposit tokens * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _payer Owner of tokens * @param _index Index of the sub stake * @param _value Amount of tokens to deposit * @param _periods Amount of periods during which tokens will be locked */ function deposit(address _staker, address _payer, uint256 _index, uint256 _value, uint16 _periods) internal { require(_value != 0); StakerInfo storage info = stakerInfo[_staker]; // A staker can't be a worker for another staker require(stakerFromWorker[_staker] == address(0) || stakerFromWorker[_staker] == info.worker); // initial stake of the staker if (info.subStakes.length == 0) { stakers.push(_staker); policyManager.register(_staker, getCurrentPeriod() - 1); } token.safeTransferFrom(_payer, address(this), _value); info.value += _value; lock(_staker, _index, _value, _periods); addSnapshot(info, int256(_value)); if (_index >= MAX_SUB_STAKES) { emit Deposited(_staker, _value, _periods); } else { uint16 lastPeriod = getLastPeriodOfSubStake(_staker, _index); emit Deposited(_staker, _value, lastPeriod - getCurrentPeriod()); } } /** * @notice Lock some tokens as a new sub-stake * @param _value Amount of tokens which will be locked * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate(uint256 _value, uint16 _periods) external onlyStaker { lock(msg.sender, MAX_SUB_STAKES, _value, _periods); } /** * @notice Increase lock amount of an existing sub-stake * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease(uint256 _index, uint256 _value) external onlyStaker { require(_index < MAX_SUB_STAKES); lock(msg.sender, _index, _value, 0); } /** * @notice Lock some tokens as a stake * @dev Specify either index and zero periods (for an existing sub-stake) * or index >= MAX_SUB_STAKES and real value for periods (for a new sub-stake), not both * @param _staker Staker * @param _index Index of the sub stake * @param _value Amount of tokens which will be locked * @param _periods Amount of periods during which tokens will be locked */ function lock(address _staker, uint256 _index, uint256 _value, uint16 _periods) internal { if (_index < MAX_SUB_STAKES) { require(_value > 0); } else { require(_value >= minAllowableLockedTokens && _periods >= minLockedPeriods); } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[_staker]; uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); uint256 requestedLockedTokens = _value.add(lockedTokens); require(requestedLockedTokens <= info.value && requestedLockedTokens <= maxAllowableLockedTokens); // next period is committed if (info.nextCommittedPeriod == nextPeriod) { lockedPerPeriod[nextPeriod] += _value; emit CommitmentMade(_staker, nextPeriod, _value); } // if index was provided then increase existing sub-stake if (_index < MAX_SUB_STAKES) { lockAndIncrease(info, currentPeriod, nextPeriod, _staker, _index, _value); // otherwise create new } else { lockAndCreate(info, nextPeriod, _staker, _value, _periods); } } /** * @notice Lock some tokens as a new sub-stake * @param _info Staker structure * @param _nextPeriod Next period * @param _staker Staker * @param _value Amount of tokens which will be locked * @param _periods Amount of periods during which tokens will be locked */ function lockAndCreate( StakerInfo storage _info, uint16 _nextPeriod, address _staker, uint256 _value, uint16 _periods ) internal { uint16 duration = _periods; // if winding down is enabled and next period is committed // then sub-stakes duration were decreased if (_info.nextCommittedPeriod == _nextPeriod && _info.flags.bitSet(WIND_DOWN_INDEX)) { duration -= 1; } saveSubStake(_info, _nextPeriod, 0, duration, _value); emit Locked(_staker, _value, _nextPeriod, _periods); } /** * @notice Increase lock amount of an existing sub-stake * @dev Probably will be created a new sub-stake but it will be active only one period * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _staker Staker * @param _index Index of the sub-stake * @param _value Amount of tokens which will be locked */ function lockAndIncrease( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, address _staker, uint256 _index, uint256 _value ) internal { SubStakeInfo storage subStake = _info.subStakes[_index]; (, uint16 lastPeriod) = checkLastPeriodOfSubStake(_info, subStake, _currentPeriod); // create temporary sub-stake for current or previous committed periods // to leave locked amount in this period unchanged if (_info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod <= _currentPeriod || _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod <= _currentPeriod) { saveSubStake(_info, subStake.firstPeriod, _currentPeriod, 0, subStake.lockedValue); } subStake.lockedValue += uint128(_value); // all new locks should start from the next period subStake.firstPeriod = _nextPeriod; emit Locked(_staker, _value, _nextPeriod, lastPeriod - _currentPeriod); } /** * @notice Checks that last period of sub-stake is greater than the current period * @param _info Staker structure * @param _subStake Sub-stake structure * @param _currentPeriod Current period * @return startPeriod Start period. Use in the calculation of the last period of the sub stake * @return lastPeriod Last period of the sub stake */ function checkLastPeriodOfSubStake( StakerInfo storage _info, SubStakeInfo storage _subStake, uint16 _currentPeriod ) internal view returns (uint16 startPeriod, uint16 lastPeriod) { startPeriod = getStartPeriod(_info, _currentPeriod); lastPeriod = getLastPeriodOfSubStake(_subStake, startPeriod); // The sub stake must be active at least in the next period require(lastPeriod > _currentPeriod); } /** * @notice Save sub stake. First tries to override inactive sub stake * @dev Inactive sub stake means that last period of sub stake has been surpassed and already rewarded * @param _info Staker structure * @param _firstPeriod First period of the sub stake * @param _lastPeriod Last period of the sub stake * @param _periods Duration of the sub stake in periods * @param _lockedValue Amount of locked tokens */ function saveSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint16 _lastPeriod, uint16 _periods, uint256 _lockedValue ) internal { for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod != 0 && (_info.currentCommittedPeriod == 0 || subStake.lastPeriod < _info.currentCommittedPeriod) && (_info.nextCommittedPeriod == 0 || subStake.lastPeriod < _info.nextCommittedPeriod)) { subStake.firstPeriod = _firstPeriod; subStake.lastPeriod = _lastPeriod; subStake.periods = _periods; subStake.lockedValue = uint128(_lockedValue); return; } } require(_info.subStakes.length < MAX_SUB_STAKES); _info.subStakes.push(SubStakeInfo(_firstPeriod, _lastPeriod, _periods, uint128(_lockedValue))); } /** * @notice Divide sub stake into two parts * @param _index Index of the sub stake * @param _newValue New sub stake value * @param _periods Amount of periods for extending sub stake */ function divideStake(uint256 _index, uint256 _newValue, uint16 _periods) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; require(_newValue >= minAllowableLockedTokens && _periods > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); uint256 oldValue = subStake.lockedValue; subStake.lockedValue = uint128(oldValue.sub(_newValue)); require(subStake.lockedValue >= minAllowableLockedTokens); uint16 requestedPeriods = subStake.periods.add16(_periods); saveSubStake(info, subStake.firstPeriod, 0, requestedPeriods, _newValue); emit Divided(msg.sender, oldValue, lastPeriod, _newValue, _periods); emit Locked(msg.sender, _newValue, subStake.firstPeriod, requestedPeriods); } /** * @notice Prolong active sub stake * @param _index Index of the sub stake * @param _periods Amount of periods for extending sub stake */ function prolongStake(uint256 _index, uint16 _periods) external onlyStaker { StakerInfo storage info = stakerInfo[msg.sender]; // Incorrect parameters require(_periods > 0); SubStakeInfo storage subStake = info.subStakes[_index]; uint16 currentPeriod = getCurrentPeriod(); (uint16 startPeriod, uint16 lastPeriod) = checkLastPeriodOfSubStake(info, subStake, currentPeriod); subStake.periods = subStake.periods.add16(_periods); // if the sub stake ends in the next committed period then reset the `lastPeriod` field if (lastPeriod == startPeriod) { subStake.lastPeriod = 0; } // The extended sub stake must not be less than the minimum value require(uint32(lastPeriod - currentPeriod) + _periods >= minLockedPeriods); emit Locked(msg.sender, subStake.lockedValue, lastPeriod + 1, _periods); emit Prolonged(msg.sender, subStake.lockedValue, lastPeriod, _periods); } /** * @notice Merge two sub-stakes into one if their last periods are equal * @dev It's possible that both sub-stakes will be active after this transaction. * But only one of them will be active until next call `commitToNextPeriod` (in the next period) * @param _index1 Index of the first sub-stake * @param _index2 Index of the second sub-stake */ function mergeStake(uint256 _index1, uint256 _index2) external onlyStaker { require(_index1 != _index2); // must be different sub-stakes StakerInfo storage info = stakerInfo[msg.sender]; SubStakeInfo storage subStake1 = info.subStakes[_index1]; SubStakeInfo storage subStake2 = info.subStakes[_index2]; uint16 currentPeriod = getCurrentPeriod(); (, uint16 lastPeriod1) = checkLastPeriodOfSubStake(info, subStake1, currentPeriod); (, uint16 lastPeriod2) = checkLastPeriodOfSubStake(info, subStake2, currentPeriod); // both sub-stakes must have equal last period to be mergeable require(lastPeriod1 == lastPeriod2); emit Merged(msg.sender, subStake1.lockedValue, subStake2.lockedValue, lastPeriod1); if (subStake1.firstPeriod == subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = 1; subStake2.periods = 0; } else if (subStake1.firstPeriod > subStake2.firstPeriod) { subStake1.lockedValue += subStake2.lockedValue; subStake2.lastPeriod = subStake1.firstPeriod - 1; subStake2.periods = 0; } else { subStake2.lockedValue += subStake1.lockedValue; subStake1.lastPeriod = subStake2.firstPeriod - 1; subStake1.periods = 0; } } /** * @notice Withdraw available amount of tokens to staker * @param _value Amount of tokens to withdraw */ function withdraw(uint256 _value) external onlyStaker { uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; StakerInfo storage info = stakerInfo[msg.sender]; // the max locked tokens in most cases will be in the current period // but when the staker locks more then we should use the next period uint256 lockedTokens = Math.max(getLockedTokens(info, currentPeriod, nextPeriod), getLockedTokens(info, currentPeriod, currentPeriod)); require(_value <= info.value.sub(lockedTokens)); info.value -= _value; addSnapshot(info, - int256(_value)); token.safeTransfer(msg.sender, _value); emit Withdrawn(msg.sender, _value); // unbond worker if staker withdraws last portion of NU if (info.value == 0 && info.nextCommittedPeriod == 0 && info.worker != address(0)) { stakerFromWorker[info.worker] = address(0); info.worker = address(0); emit WorkerBonded(msg.sender, address(0), currentPeriod); } } /** * @notice Make a commitment to the next period and mint for the previous period */ function commitToNextPeriod() external isInitialized { address staker = stakerFromWorker[msg.sender]; StakerInfo storage info = stakerInfo[staker]; // Staker must have a stake to make a commitment require(info.value > 0); // Only worker with real address can make a commitment require(msg.sender == tx.origin); uint16 lastCommittedPeriod = getLastCommittedPeriod(staker); mint(staker); uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; // the period has already been committed if (info.nextCommittedPeriod == nextPeriod) { return; } uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod); require(lockedTokens > 0); lockedPerPeriod[nextPeriod] += lockedTokens; info.currentCommittedPeriod = info.nextCommittedPeriod; info.nextCommittedPeriod = nextPeriod; decreaseSubStakesDuration(info, nextPeriod); // staker was inactive for several periods if (lastCommittedPeriod < currentPeriod) { info.pastDowntime.push(Downtime(lastCommittedPeriod + 1, currentPeriod)); } policyManager.setDefaultFeeDelta(staker, nextPeriod); emit CommitmentMade(staker, nextPeriod, lockedTokens); } /** * @notice Decrease sub-stakes duration if `windDown` is enabled */ function decreaseSubStakesDuration(StakerInfo storage _info, uint16 _nextPeriod) internal { if (!_info.flags.bitSet(WIND_DOWN_INDEX)) { return; } for (uint256 index = 0; index < _info.subStakes.length; index++) { SubStakeInfo storage subStake = _info.subStakes[index]; if (subStake.lastPeriod != 0 || subStake.periods == 0) { continue; } subStake.periods--; if (subStake.periods == 0) { subStake.lastPeriod = _nextPeriod; } } } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment */ function mint() external onlyStaker { // save last committed period to the storage if both periods will be empty after minting // because we won't be able to calculate last committed period // see getLastCommittedPeriod(address) StakerInfo storage info = stakerInfo[msg.sender]; uint16 previousPeriod = getCurrentPeriod() - 1; if (info.nextCommittedPeriod <= previousPeriod && info.nextCommittedPeriod != 0) { info.lastCommittedPeriod = info.nextCommittedPeriod; } mint(msg.sender); } /** * @notice Mint tokens for previous periods if staker locked their tokens and made a commitment * @param _staker Staker */ function mint(address _staker) internal { uint16 currentPeriod = getCurrentPeriod(); uint16 previousPeriod = currentPeriod - 1; StakerInfo storage info = stakerInfo[_staker]; if (info.nextCommittedPeriod == 0 || info.currentCommittedPeriod == 0 && info.nextCommittedPeriod > previousPeriod || info.currentCommittedPeriod > previousPeriod) { return; } uint16 startPeriod = getStartPeriod(info, currentPeriod); uint256 reward = 0; bool reStake = !info.flags.bitSet(RE_STAKE_DISABLED_INDEX); if (info.currentCommittedPeriod != 0) { reward = mint(_staker, info, info.currentCommittedPeriod, currentPeriod, startPeriod, reStake); info.currentCommittedPeriod = 0; if (reStake) { lockedPerPeriod[info.nextCommittedPeriod] += reward; } } if (info.nextCommittedPeriod <= previousPeriod) { reward += mint(_staker, info, info.nextCommittedPeriod, currentPeriod, startPeriod, reStake); info.nextCommittedPeriod = 0; } info.value += reward; if (info.flags.bitSet(MEASURE_WORK_INDEX)) { info.completedWork += reward; } addSnapshot(info, int256(reward)); emit Minted(_staker, previousPeriod, reward); } /** * @notice Calculate reward for one period * @param _staker Staker's address * @param _info Staker structure * @param _mintingPeriod Period for minting calculation * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period */ function mint( address _staker, StakerInfo storage _info, uint16 _mintingPeriod, uint16 _currentPeriod, uint16 _startPeriod, bool _reStake ) internal returns (uint256 reward) { reward = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (subStake.firstPeriod <= _mintingPeriod && lastPeriod >= _mintingPeriod) { uint256 subStakeReward = mint( _currentPeriod, subStake.lockedValue, lockedPerPeriod[_mintingPeriod], lastPeriod.sub16(_mintingPeriod)); reward += subStakeReward; if (_reStake) { subStake.lockedValue += uint128(subStakeReward); } } } policyManager.updateFee(_staker, _mintingPeriod); return reward; } //-------------------------Slashing------------------------- /** * @notice Slash the staker's stake and reward the investigator * @param _staker Staker's address * @param _penalty Penalty * @param _investigator Investigator * @param _reward Reward for the investigator */ function slashStaker( address _staker, uint256 _penalty, address _investigator, uint256 _reward ) public isInitialized { require(msg.sender == address(adjudicator)); require(_penalty > 0); StakerInfo storage info = stakerInfo[_staker]; if (info.value <= _penalty) { _penalty = info.value; } info.value -= _penalty; if (_reward > _penalty) { _reward = _penalty; } uint16 currentPeriod = getCurrentPeriod(); uint16 nextPeriod = currentPeriod + 1; uint16 startPeriod = getStartPeriod(info, currentPeriod); (uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex) = getLockedTokensAndShortestSubStake(info, currentPeriod, nextPeriod, startPeriod); // Decrease the stake if amount of locked tokens in the current period more than staker has uint256 lockedTokens = currentLock + currentAndNextLock; if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, currentPeriod, startPeriod, shortestSubStakeIndex); } // Decrease the stake if amount of locked tokens in the next period more than staker has if (nextLock > 0) { lockedTokens = nextLock + currentAndNextLock - (currentAndNextLock > info.value ? currentAndNextLock - info.value : 0); if (info.value < lockedTokens) { decreaseSubStakes(info, lockedTokens - info.value, nextPeriod, startPeriod, MAX_SUB_STAKES); } } emit Slashed(_staker, _penalty, _investigator, _reward); if (_penalty > _reward) { unMint(_penalty - _reward); } // TODO change to withdrawal pattern (#1499) if (_reward > 0) { token.safeTransfer(_investigator, _reward); } addSnapshot(info, - int256(_penalty)); } /** * @notice Get the value of locked tokens for a staker in the current and the next period * and find the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _nextPeriod Next period * @param _startPeriod Pre-calculated start period * @return currentLock Amount of tokens that locked in the current period and unlocked in the next period * @return nextLock Amount of tokens that locked in the next period and not locked in the current period * @return currentAndNextLock Amount of tokens that locked in the current period and in the next period * @return shortestSubStakeIndex Index of the shortest sub stake */ function getLockedTokensAndShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _nextPeriod, uint16 _startPeriod ) internal view returns ( uint256 currentLock, uint256 nextLock, uint256 currentAndNextLock, uint256 shortestSubStakeIndex ) { uint16 minDuration = MAX_UINT16; uint16 minLastPeriod = MAX_UINT16; shortestSubStakeIndex = MAX_SUB_STAKES; currentLock = 0; nextLock = 0; currentAndNextLock = 0; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _nextPeriod) { currentAndNextLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod) { currentLock += subStake.lockedValue; } else if (subStake.firstPeriod <= _nextPeriod && lastPeriod >= _nextPeriod) { nextLock += subStake.lockedValue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minLastPeriod || lastPeriod == minLastPeriod && duration < minDuration)) { shortestSubStakeIndex = i; minDuration = duration; minLastPeriod = lastPeriod; } } } /** * @notice Decrease short sub stakes * @param _info Staker structure * @param _penalty Penalty rate * @param _decreasePeriod The period when the decrease begins * @param _startPeriod Pre-calculated start period * @param _shortestSubStakeIndex Index of the shortest period */ function decreaseSubStakes( StakerInfo storage _info, uint256 _penalty, uint16 _decreasePeriod, uint16 _startPeriod, uint256 _shortestSubStakeIndex ) internal { SubStakeInfo storage shortestSubStake = _info.subStakes[0]; uint16 minSubStakeLastPeriod = MAX_UINT16; uint16 minSubStakeDuration = MAX_UINT16; while(_penalty > 0) { if (_shortestSubStakeIndex < MAX_SUB_STAKES) { shortestSubStake = _info.subStakes[_shortestSubStakeIndex]; minSubStakeLastPeriod = getLastPeriodOfSubStake(shortestSubStake, _startPeriod); minSubStakeDuration = minSubStakeLastPeriod - shortestSubStake.firstPeriod; _shortestSubStakeIndex = MAX_SUB_STAKES; } else { (shortestSubStake, minSubStakeDuration, minSubStakeLastPeriod) = getShortestSubStake(_info, _decreasePeriod, _startPeriod); } if (minSubStakeDuration == MAX_UINT16) { break; } uint256 appliedPenalty = _penalty; if (_penalty < shortestSubStake.lockedValue) { shortestSubStake.lockedValue -= uint128(_penalty); saveOldSubStake(_info, shortestSubStake.firstPeriod, _penalty, _decreasePeriod); _penalty = 0; } else { shortestSubStake.lastPeriod = _decreasePeriod - 1; _penalty -= shortestSubStake.lockedValue; appliedPenalty = shortestSubStake.lockedValue; } if (_info.currentCommittedPeriod >= _decreasePeriod && _info.currentCommittedPeriod <= minSubStakeLastPeriod) { lockedPerPeriod[_info.currentCommittedPeriod] -= appliedPenalty; } if (_info.nextCommittedPeriod >= _decreasePeriod && _info.nextCommittedPeriod <= minSubStakeLastPeriod) { lockedPerPeriod[_info.nextCommittedPeriod] -= appliedPenalty; } } } /** * @notice Get the shortest sub stake * @param _info Staker structure * @param _currentPeriod Current period * @param _startPeriod Pre-calculated start period * @return shortestSubStake The shortest sub stake * @return minSubStakeDuration Duration of the shortest sub stake * @return minSubStakeLastPeriod Last period of the shortest sub stake */ function getShortestSubStake( StakerInfo storage _info, uint16 _currentPeriod, uint16 _startPeriod ) internal view returns ( SubStakeInfo storage shortestSubStake, uint16 minSubStakeDuration, uint16 minSubStakeLastPeriod ) { shortestSubStake = shortestSubStake; minSubStakeDuration = MAX_UINT16; minSubStakeLastPeriod = MAX_UINT16; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; uint16 lastPeriod = getLastPeriodOfSubStake(subStake, _startPeriod); if (lastPeriod < subStake.firstPeriod) { continue; } uint16 duration = lastPeriod - subStake.firstPeriod; if (subStake.firstPeriod <= _currentPeriod && lastPeriod >= _currentPeriod && (lastPeriod < minSubStakeLastPeriod || lastPeriod == minSubStakeLastPeriod && duration < minSubStakeDuration)) { shortestSubStake = subStake; minSubStakeDuration = duration; minSubStakeLastPeriod = lastPeriod; } } } /** * @notice Save the old sub stake values to prevent decreasing reward for the previous period * @dev Saving happens only if the previous period is committed * @param _info Staker structure * @param _firstPeriod First period of the old sub stake * @param _lockedValue Locked value of the old sub stake * @param _currentPeriod Current period, when the old sub stake is already unlocked */ function saveOldSubStake( StakerInfo storage _info, uint16 _firstPeriod, uint256 _lockedValue, uint16 _currentPeriod ) internal { // Check that the old sub stake should be saved bool oldCurrentCommittedPeriod = _info.currentCommittedPeriod != 0 && _info.currentCommittedPeriod < _currentPeriod; bool oldnextCommittedPeriod = _info.nextCommittedPeriod != 0 && _info.nextCommittedPeriod < _currentPeriod; bool crosscurrentCommittedPeriod = oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= _firstPeriod; bool crossnextCommittedPeriod = oldnextCommittedPeriod && _info.nextCommittedPeriod >= _firstPeriod; if (!crosscurrentCommittedPeriod && !crossnextCommittedPeriod) { return; } // Try to find already existent proper old sub stake uint16 previousPeriod = _currentPeriod - 1; for (uint256 i = 0; i < _info.subStakes.length; i++) { SubStakeInfo storage subStake = _info.subStakes[i]; if (subStake.lastPeriod == previousPeriod && ((crosscurrentCommittedPeriod == (oldCurrentCommittedPeriod && _info.currentCommittedPeriod >= subStake.firstPeriod)) && (crossnextCommittedPeriod == (oldnextCommittedPeriod && _info.nextCommittedPeriod >= subStake.firstPeriod)))) { subStake.lockedValue += uint128(_lockedValue); return; } } saveSubStake(_info, _firstPeriod, previousPeriod, 0, _lockedValue); } //-------------Additional getters for stakers info------------- /** * @notice Return the length of the array of stakers */ function getStakersLength() external view returns (uint256) { return stakers.length; } /** * @notice Return the length of the array of sub stakes */ function getSubStakesLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].subStakes.length; } /** * @notice Return the information about sub stake */ function getSubStakeInfo(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (SubStakeInfo) // TODO "virtual" only for tests, probably will be removed after #1512 external view virtual returns (uint16 firstPeriod, uint16 lastPeriod, uint16 periods, uint128 lockedValue) { SubStakeInfo storage info = stakerInfo[_staker].subStakes[_index]; firstPeriod = info.firstPeriod; lastPeriod = info.lastPeriod; periods = info.periods; lockedValue = info.lockedValue; } /** * @notice Return the length of the array of past downtime */ function getPastDowntimeLength(address _staker) external view returns (uint256) { return stakerInfo[_staker].pastDowntime.length; } /** * @notice Return the information about past downtime */ function getPastDowntime(address _staker, uint256 _index) // TODO change to structure when ABIEncoderV2 is released (#1501) // public view returns (Downtime) external view returns (uint16 startPeriod, uint16 endPeriod) { Downtime storage downtime = stakerInfo[_staker].pastDowntime[_index]; startPeriod = downtime.startPeriod; endPeriod = downtime.endPeriod; } //------------------ ERC900 connectors ---------------------- function totalStakedForAt(address _owner, uint256 _blockNumber) public view override returns (uint256){ return stakerInfo[_owner].history.getValueAt(_blockNumber); } function totalStakedAt(uint256 _blockNumber) public view override returns (uint256){ return balanceHistory.getValueAt(_blockNumber); } function supportsHistory() external pure override returns (bool){ return true; } //------------------------Upgradeable------------------------ /** * @dev Get StakerInfo structure by delegatecall */ function delegateGetStakerInfo(address _target, bytes32 _staker) internal returns (StakerInfo memory result) { bytes32 memoryAddress = delegateGetData(_target, this.stakerInfo.selector, 1, _staker, 0); assembly { result := memoryAddress } } /** * @dev Get SubStakeInfo structure by delegatecall */ function delegateGetSubStakeInfo(address _target, bytes32 _staker, uint256 _index) internal returns (SubStakeInfo memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getSubStakeInfo.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /** * @dev Get Downtime structure by delegatecall */ function delegateGetPastDowntime(address _target, bytes32 _staker, uint256 _index) internal returns (Downtime memory result) { bytes32 memoryAddress = delegateGetData( _target, this.getPastDowntime.selector, 2, _staker, bytes32(_index)); assembly { result := memoryAddress } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `verifyState` function verifyState(address _testTarget) public override virtual { super.verifyState(_testTarget); require(address(delegateGet(_testTarget, this.policyManager.selector)) == address(policyManager)); require(address(delegateGet(_testTarget, this.adjudicator.selector)) == address(adjudicator)); require(address(delegateGet(_testTarget, this.workLock.selector)) == address(workLock)); require(delegateGet(_testTarget, this.lockedPerPeriod.selector, bytes32(bytes2(RESERVED_PERIOD))) == lockedPerPeriod[RESERVED_PERIOD]); require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(0))) == stakerFromWorker[address(0)]); require(delegateGet(_testTarget, this.getStakersLength.selector) == stakers.length); if (stakers.length == 0) { return; } address stakerAddress = stakers[0]; require(address(uint160(delegateGet(_testTarget, this.stakers.selector, 0))) == stakerAddress); StakerInfo storage info = stakerInfo[stakerAddress]; bytes32 staker = bytes32(uint256(stakerAddress)); StakerInfo memory infoToCheck = delegateGetStakerInfo(_testTarget, staker); require(infoToCheck.value == info.value && infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod && infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod && infoToCheck.flags == info.flags && infoToCheck.lockReStakeUntilPeriod == info.lockReStakeUntilPeriod && infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod && infoToCheck.completedWork == info.completedWork && infoToCheck.worker == info.worker && infoToCheck.workerStartPeriod == info.workerStartPeriod); require(delegateGet(_testTarget, this.getPastDowntimeLength.selector, staker) == info.pastDowntime.length); for (uint256 i = 0; i < info.pastDowntime.length && i < MAX_CHECKED_VALUES; i++) { Downtime storage downtime = info.pastDowntime[i]; Downtime memory downtimeToCheck = delegateGetPastDowntime(_testTarget, staker, i); require(downtimeToCheck.startPeriod == downtime.startPeriod && downtimeToCheck.endPeriod == downtime.endPeriod); } require(delegateGet(_testTarget, this.getSubStakesLength.selector, staker) == info.subStakes.length); for (uint256 i = 0; i < info.subStakes.length && i < MAX_CHECKED_VALUES; i++) { SubStakeInfo storage subStakeInfo = info.subStakes[i]; SubStakeInfo memory subStakeInfoToCheck = delegateGetSubStakeInfo(_testTarget, staker, i); require(subStakeInfoToCheck.firstPeriod == subStakeInfo.firstPeriod && subStakeInfoToCheck.lastPeriod == subStakeInfo.lastPeriod && subStakeInfoToCheck.periods == subStakeInfo.periods && subStakeInfoToCheck.lockedValue == subStakeInfo.lockedValue); } // it's not perfect because checks not only slot value but also decoding // at least without additional functions require(delegateGet(_testTarget, this.totalStakedForAt.selector, staker, bytes32(block.number)) == totalStakedForAt(stakerAddress, block.number)); require(delegateGet(_testTarget, this.totalStakedAt.selector, bytes32(block.number)) == totalStakedAt(block.number)); if (info.worker != address(0)) { require(address(delegateGet(_testTarget, this.stakerFromWorker.selector, bytes32(uint256(info.worker)))) == stakerFromWorker[info.worker]); } } /// @dev the `onlyWhileUpgrading` modifier works through a call to the parent `finishUpgrade` function finishUpgrade(address _target) public override virtual { super.finishUpgrade(_target); // Create fake period lockedPerPeriod[RESERVED_PERIOD] = 111; // Create fake worker stakerFromWorker[address(0)] = address(this); } }
0x608060405234801561001057600080fd5b50600436106101165760003560e01c80638f32d59b116100a2578063e2fdcc1711610071578063e2fdcc1714610679578063e38a303b14610681578063e8dccd061461069f578063f2fde38b146106c5578063fc9daa07146106eb57610116565b80638f32d59b1461063b578063b9626d2114610643578063bd02b14014610669578063d4b839921461067157610116565b806359a15fa5116100e957806359a15fa5146105ab5780635d5b6836146105d457806370535443146105fa578063715018a61461062b5780638da5cb5b1461063357610116565b80630bea809b1461011b5780631f96670b146105655780634b2cd1181461057f5780635712e98c146105a3575b600080fd5b610563600480360361010081101561013257600080fd5b810190602081018135600160201b81111561014c57600080fd5b82018360208201111561015e57600080fd5b803590602001918460018302840111600160201b8311171561017f57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b8111156101d157600080fd5b8201836020820111156101e357600080fd5b803590602001918460018302840111600160201b8311171561020457600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b81111561025657600080fd5b82018360208201111561026857600080fd5b803590602001918460018302840111600160201b8311171561028957600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b8111156102db57600080fd5b8201836020820111156102ed57600080fd5b803590602001918460018302840111600160201b8311171561030e57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b81111561036057600080fd5b82018360208201111561037257600080fd5b803590602001918460018302840111600160201b8311171561039357600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b8111156103e557600080fd5b8201836020820111156103f757600080fd5b803590602001918460018302840111600160201b8311171561041857600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b81111561046a57600080fd5b82018360208201111561047c57600080fd5b803590602001918460018302840111600160201b8311171561049d57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b8111156104ef57600080fd5b82018360208201111561050157600080fd5b803590602001918460018302840111600160201b8311171561052257600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295506106f3945050505050565b005b61056d6110a2565b60408051918252519081900360200190f35b6105876110c6565b604080516001600160a01b039092168252519081900360200190f35b61056d6110d5565b6105b36110f9565b604051808260028111156105c357fe5b815260200191505060405180910390f35b61056d600480360360208110156105ea57600080fd5b50356001600160a01b031661111d565b6106176004803603602081101561061057600080fd5b503561112f565b604080519115158252519081900360200190f35b610563611144565b61058761119f565b6106176111ae565b6105636004803603602081101561065957600080fd5b50356001600160a01b03166111bf565b61056d611282565b6105876112a6565b6105876112b5565b6106896112d9565b6040805160ff9092168252519081900360200190f35b610563600480360360208110156106b557600080fd5b50356001600160a01b03166112e9565b610563600480360360208110156106db57600080fd5b50356001600160a01b0316611365565b61056d611382565b60006107cf89896040516020018083805190602001908083835b6020831061072c5780518252601f19909201916020918201910161070d565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106107745780518252601f199092019160209182019101610755565b6001836020036101000a038019825116818451168082178552505050505050905001925050506040516020818303038152906040527f00000000000000000000000000000000000000000000000000000000000000016113a6565b60008181526005602052604090205490915060ff16156108205760405162461bcd60e51b81526004018080602001828103825260268152602001806135a36026913960400191505060405180910390fd5b6000818152600560205260408120805460ff191660011790556108448a8a856114fe565b6040805182151581529051919250339184917f14c7c3aeaed5d9de50669529f936d80ff48af1f52beb8447437689cb298131a8919081900360200190a361088a85611f21565b6108db576040805162461bcd60e51b815260206004820152601e60248201527f5374616b65722773207075626c6963206b657920697320696e76616c69640000604482015290519081900360640190fd5b6108e486611f21565b61091f5760405162461bcd60e51b815260040180806020018281038252602181526020018061386a6021913960400191505060405180910390fd5b610927613333565b61093084611f81565b90506109eb8a8a836102c0015160016005811061094957fe5b1a60f81b6040516020018083805190602001908083835b6020831061097f5780518252601f199092019160209182019101610960565b6001836020036101000a038019825116818451168082178552505050505050905001826001600160f81b031916815260010192505050604051602081830303815290604052887f000000000000000000000000000000000000000000000000000000000000000161215f565b610a3c576040805162461bcd60e51b815260206004820152601a60248201527f4346726167207369676e617475726520697320696e76616c6964000000000000604482015290519081900360640190fd5b610a446133f7565b610a4d8b6121a7565b9050610b1089826080015160c00151846102c00151600260058110610a6e57fe5b1a60f81b6040516020018083805190602001908083835b60208310610aa45780518252601f199092019160209182019101610a85565b6001836020036101000a038019825116818451168082178552505050505050905001826001600160f81b031916815260010192505050604051602081830303815290604052897f000000000000000000000000000000000000000000000000000000000000000161215f565b610b61576040805162461bcd60e51b815260206004820152601960248201527f5461736b207369676e617475726520697320696e76616c696400000000000000604482015290519081900360640190fd5b60208701516102c083015160609060041a60f81b8260405160200180836001600160f81b0319168152600101828152602001925050506040516020818303038152906040529050610d7f8e828a876102a001516000801b6040516020018086805190602001908083835b60208310610bea5780518252601f199092019160209182019101610bcb565b51815160209384036101000a600019018019909216911617905288519190930192880191508083835b60208310610c325780518252601f199092019160209182019101610c13565b51815160209384036101000a600019018019909216911617905287519190930192870191508083835b60208310610c7a5780518252601f199092019160209182019101610c5b565b6001836020036101000a038019825116818451168082178552505050505050905001836001600160a01b031660601b8152601401828152602001955050505050506040516020818303038152906040528c866102c00151600360058110610cdd57fe5b1a60f81b6040516020018083805190602001908083835b60208310610d135780518252601f199092019160209182019101610cf4565b6001836020036101000a038019825116818451168082178552505050505050905001826001600160f81b0319168152600101925050506040516020818303038152906040528c7f000000000000000000000000000000000000000000000000000000000000000161215f565b610dba5760405162461bcd60e51b81526004018080602001828103825260228152602001806135816022913960400191505060405180910390fd5b6000610dd3610dcd83604560f81b61222f565b8a61253b565b905060007f000000000000000000000000bbd3c0c794f40c4f993b03f65343acc6fcfcb2e26001600160a01b031663b2eeb36e836040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015610e4457600080fd5b505afa158015610e58573d6000803e3d6000fd5b505050506040513d6020811015610e6e57600080fd5b505190506001600160a01b038116610eb75760405162461bcd60e51b81526004018080602001828103825260228152602001806137296022913960400191505060405180910390fd5b60007f000000000000000000000000bbd3c0c794f40c4f993b03f65343acc6fcfcb2e26001600160a01b031663178b6de6836040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015610f2657600080fd5b505afa158015610f3a573d6000803e3d6000fd5b505050506040513d6020811015610f5057600080fd5b5051905080610f9d576040805162461bcd60e51b81526020600482015260146024820152735374616b657220686173206e6f20746f6b656e7360601b604482015290519081900360640190fd5b8761108f57600080610faf84846125f7565b60408051632673086360e21b81526001600160a01b038881166004830152602482018590523360448301526064820184905291519395509193507f000000000000000000000000bbd3c0c794f40c4f993b03f65343acc6fcfcb2e216916399cc218c9160848082019260009290919082900301818387803b15801561103357600080fd5b505af1158015611047573d6000803e3d6000fd5b50505050836001600160a01b0316856001600160a01b03168c7f860028d7f53afb628cae3582337c99be24159f7ee9d68a96babbc7f054a36caf60405160405180910390a450505b5050505050505050505050505050505050565b7f000000000000000000000000000000000000000000000000000000000000000081565b6002546001600160a01b031681565b7f000000000000000000000000000000000000000000000000000000000000000281565b7f000000000000000000000000000000000000000000000000000000000000000181565b60046020526000908152604090205481565b60056020526000908152604090205460ff1681565b61114c6111ae565b61115557600080fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b6000546001600160a01b031690565b6000546001600160a01b0316331490565b6111c881612712565b6040805160006020808301829052835180840390910181529183019092526111f19060016113a6565b60008181526005602052604090205490915060ff16611211576000611214565b60015b60ff1661122983637053544360e01b8461276c565b1461123357600080fd5b600080805260046020527f17ef568e3e12ab5b9c7254a8d58478811de00f9e6eb34345acd53bf8fd09d3ec5490611274908490632eadb41b60e11b9061276c565b1461127e57600080fd5b5050565b7f00000000000000000000000000000000000000000000000000000000000186a081565b6001546001600160a01b031681565b7f000000000000000000000000bbd3c0c794f40c4f993b03f65343acc6fcfcb2e281565b600254600160a01b900460ff1681565b6112f281612787565b60408051600060208083018290528351808403909101815291830190925261131b9060016113a6565b60009081526005602090815260408220805460ff19166001179055908052600490525050607b7f17ef568e3e12ab5b9c7254a8d58478811de00f9e6eb34345acd53bf8fd09d3ec55565b61136d6111ae565b61137657600080fd5b61137f816127e1565b50565b7f000000000000000000000000000000000000000000000000000000000000000281565b6000808260028111156113b557fe5b14156113c85750815160208301206114f8565b60018260028111156113d657fe5b141561146b576002836040518082805190602001908083835b6020831061140e5780518252601f1990920191602091820191016113ef565b51815160209384036101000a60001901801990921691161790526040519190930194509192505080830381855afa15801561144d573d6000803e3d6000fd5b5050506040513d602081101561146257600080fd5b505190506114f8565b6003836040518082805190602001908083835b6020831061149d5780518252601f19909201916020918201910161147e565b51815160209384036101000a60001901801990921691161790526040519190930194509192505080830381855afa1580156114dc573d6000803e3d6000fd5b5050506040515160601b6bffffffffffffffffffffffff191690505b92915050565b600061150861343d565b6115118561284f565b905061151b6133f7565b611524856121a7565b905061152e613333565b61153785611f81565b905060006115df826102800151846080015160a00151846102c0015160006005811061155f57fe5b1a60f81b6040516020018083805190602001908083835b602083106115955780518252601f199092019160209182019101611576565b6001836020036101000a038019825116818451168082178552505050505050905001826001600160f81b03191681526001019250505060405160208183030381529060405261253b565b9050816102a001516001600160a01b0316816001600160a01b031614611642576040805162461bcd60e51b8152602060048201526013602482015272426164204b46726167207369676e617475726560681b604482015290519081900360640190fd5b600061164e85856128a6565b85518051602090910151855192935061166692612b44565b6116a15760405162461bcd60e51b815260040180806020018281038252604681526020018061369d6046913960600191505060405180910390fd5b6116b383602001518460400151612b61565b611704576040805162461bcd60e51b815260206004820181905260248201527f506f696e74207a45206973206e6f7420612076616c696420454320706f696e74604482015290519081900360640190fd5b61172d856000015160200151846000015186608001516080015186602001518760400151612bc6565b6117685760405162461bcd60e51b81526004018080602001828103825260228152602001806135176022913960400191505060405180910390fd5b835180516020909101516060850151611782929190612b44565b6117bd5760405162461bcd60e51b81526004018080602001828103825260488152602001806137ba6048913960600191505060405180910390fd5b6117cf83608001518460a00151612b61565b61180a5760405162461bcd60e51b81526004018080602001828103825260228152602001806138026022913960400191505060405180910390fd5b61182b84600001516020015184606001518386608001518760a00151612bc6565b6118665760405162461bcd60e51b81526004018080602001828103825260238152602001806139186023913960400191505060405180910390fd5b608084015151805160209091015160c0850151611884929190612b44565b6118bf5760405162461bcd60e51b81526004018080602001828103825260488152602001806138d06048913960600191505060405180910390fd5b6000611930604051806040016040528086602001518152602001866040015181525061192b60405180604001604052808960800151600001516020015181526020018860c001518152506040518060400160405280896080015181526020018960a00151815250612c92565b612dba565b9050806119465760009650505050505050611f1a565b602080870151805191015160e0860151611961929190612b44565b61199c5760405162461bcd60e51b81526004018080602001828103825260468152602001806136e36046913960600191505060405180910390fd5b6119b0846101000151856101200151612b61565b611a01576040805162461bcd60e51b815260206004820181905260248201527f506f696e74207a56206973206e6f7420612076616c696420454320706f696e74604482015290519081900360640190fd5b611a2c8660200151602001518560e00151876080015160800151876101000151886101200151612bc6565b611a675760405162461bcd60e51b81526004018080602001828103825260228152602001806136116022913960400191505060405180910390fd5b6020808601518051910151610140860151611a83929190612b44565b611abe5760405162461bcd60e51b815260040180806020018281038252604881526020018061374b6048913960600191505060405180910390fd5b611ad2846101600151856101800151612b61565b611b0d5760405162461bcd60e51b815260040180806020018281038252602281526020018061388b6022913960400191505060405180910390fd5b611b3185602001516020015185610140015184876101600151886101800151612bc6565b611b6c5760405162461bcd60e51b81526004018080602001828103825260238152602001806138ad6023913960400191505060405180910390fd5b608085015160209081015180519101516101a0860151611b8d929190612b44565b611bc85760405162461bcd60e51b81526004018080602001828103825260488152602001806136336048913960600191505060405180910390fd5b611c376040518060400160405280866101000151815260200186610120015181525061192b6040518060400160405280896080015160200151602001518152602001886101a0015181525060405180604001604052808961016001518152602001896101800151815250612c92565b905080611c4d5760009650505050505050611f1a565b611c61846101c00151856101e00151612b61565b611c9c5760405162461bcd60e51b81526004018080602001828103825260218152602001806138496021913960400191505060405180910390fd5b611cfb7f03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f7f7880ed56962d7c0ae44d6f14bb53b5fe64b31ea44a41d0316f3a598778f0f936876080015160800151876101c00151886101e00151612bc6565b611d365760405162461bcd60e51b815260040180806020018281038252602281526020018061367b6022913960400191505060405180910390fd5b6080850151604001518051602090910151610200860151611d58929190612b44565b611d935760405162461bcd60e51b81526004018080602001828103825260488152602001806135c96048913960600191505060405180910390fd5b611da7846102200151856102400151612b61565b611de25760405162461bcd60e51b81526004018080602001828103825260228152602001806134f56022913960400191505060405180910390fd5b611e0a8560800151604001516020015185610200015184876102200151886102400151612bc6565b611e455760405162461bcd60e51b81526004018080602001828103825260238152602001806138ad6023913960400191505060405180910390fd5b6080850151606001518051602090910151610260860151611e67929190612b44565b611ea25760405162461bcd60e51b81526004018080602001828103825260488152602001806135396048913960600191505060405180910390fd5b611f116040518060400160405280866101c001518152602001866101e0015181525061192b604051806040016040528089608001516060015160200151815260200188610260015181525060405180604001604052808961022001518152602001896102400151815250612c92565b96505050505050505b9392505050565b60008151604014611f635760405162461bcd60e51b81526004018080602001828103825260258152602001806138246025913960400191505060405180910390fd5b60208201516040830151611f778282612b61565b925050505b919050565b611f89613333565b81516102b914611f9857600080fd5b6000611fa383612e22565b905080611faf81612e28565b8352602001611fbd81612e28565b60208085019190915201611fd081612e28565b6040840152602001611fe181612e28565b6060840152602001611ff281612e28565b608084015260200161200381612e28565b60a084015260200161201481612e28565b60c084015260200161202581612e28565b60e084015260200161203681612e28565b61010084015260200161204881612e28565b61012084015260200161205a81612e28565b61014084015260200161206c81612e28565b61016084015260200161207e81612e28565b61018084015260200161209081612e28565b6101a08401526020016120a281612e28565b6101c08401526020016120b481612e28565b6101e08401526020016120c681612e28565b6102008401526020016120d881612e28565b6102208401526020016120ea81612e28565b6102408401526020016120fc81612e28565b61026084015260200161210e81612e28565b61028084015260200161212081612e28565b60601c6102a084015260140161213581612e28565b6001600160d81b0319166102c08401526005016102b98201811461215857600080fd5b5050919050565b6000825160401461216f57600080fd5b61218261217c86846113a6565b8561253b565b6001600160a01b031661219484612e2c565b6001600160a01b03161495945050505050565b6121af6133f7565b81516101678110156121c057600080fd5b60006121cb84612e22565b90506121db818460000151612e37565b90506121eb818460200151612e37565b90506121f681612e28565b6040840152606083015160209190910190612212908290612e37565b9050612222816082198401612e52565b6080840152509092915050565b60006001600160f81b031982166122e257604051601960f81b602080830182815260006021850181905230606081901b602287015288519095919386938a9390926036909101918401908083835b6020831061229c5780518252601f19909201916020918201910161227d565b6001836020036101000a038019825116818451168082178552505050505050905001945050505050604051602081830303815290604052805190602001209150506114f8565b6001600160f81b03198216604560f81b14156124ee578251806123365760405162461bcd60e51b81526004018080602001828103825260278152602001806137936027913960400191505060405180910390fd5b60005b811561234d57600101600a82049150612339565b60608167ffffffffffffffff8111801561236657600080fd5b506040519080825280601f01601f191660200182016040528015612391576020820181803683370190505b5086519350905060001982015b83156123e357600a840660300160f81b828280600190039350815181106123c157fe5b60200101906001600160f81b031916908160001a905350600a8404935061239e565b601960f81b7f457468657265756d205369676e6564204d6573736167653a0a00000000000000838960405160200180856001600160f81b03191681526001018466ffffffffffffff1916815260190183805190602001908083835b6020831061245d5780518252601f19909201916020918201910161243e565b51815160209384036101000a600019018019909216911617905285519190930192850191508083835b602083106124a55780518252601f199092019160209182019101612486565b6001836020036101000a038019825116818451168082178552505050505050905001945050505050604051602081830303815290604052805190602001209450505050506114f8565b6040805162461bcd60e51b815260206004820152601a60248201527f556e737570706f72746564204549503139312076657273696f6e000000000000604482015290519081900360640190fd5b6000815160411461254b57600080fd5b60208201516040830151606084015160001a601b81101561256a57601b015b8060ff16601b148061257f57508060ff16601c145b61258857600080fd5b60018682858560405160008152602001604052604051808581526020018460ff1681526020018381526020018281526020019450505050506020604051602081039080840390855afa1580156125e2573d6000803e3d6000fd5b5050604051601f190151979650505050505050565b6001600160a01b038216600090815260046020526040812054819061266890612641907f000000000000000000000000000000000000000000000000000000000000000090612f58565b7f000000000000000000000000000000000000000000000000000000000000000290612f7f565b915061269d82612698857f00000000000000000000000000000000000000000000000000000000000186a0612f91565b612fb3565b91506126c9827f0000000000000000000000000000000000000000000000000000000000000002612f91565b6001600160a01b0385166000908152600460205260409020549091506126f0906001612f7f565b6001600160a01b03909416600090815260046020526040902093909355929050565b60028054600160a01b900460ff161461272a57600080fd5b6040805133815290516001600160a01b038316917f1e8d98c1b4a0d9bd2e2371026b632eb2773fcce41742e41f02f574ab69868d4c919081900360200190a250565b60008061277d858560018685612fc9565b5195945050505050565b60028054600160a01b900460ff161461279f57600080fd5b6040805133815290516001600160a01b038316917fd55ec27c5c6316913ed8803c18cfd1bfefea953db909dcba6140744a9d8b0d1f919081900360200190a250565b6001600160a01b0381166127f457600080fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b61285761343d565b815160621461286557600080fd5b600061287083612e22565b9050612880818360000151612e37565b9050612890818360200151612e37565b905061289b81612e28565b604083015250919050565b81518051602091820151835180519084015160808601805151805190870151604080516001600160f81b031960f8998a1b8116828c0152602182019890985295881b871660418701526042860194909452951b909316606283015260638083019490945280518083039094018452608382019052838601518051908501518686015180519087015194518701518051908801518751600099899896979596949560a3019182918a01908083835b602083106129725780518252601f199092019160209182019101612953565b51815160209384036101000a600019018019909216911617905260f89a8b1b6001600160f81b031990811692909401918252600182019990995296891b8216602188015250602286019490945250941b166042820152604380820193909352604080518083039094018452606382018152608088015190810151805190840151606083015180519086015160c0909401518751979950899850600160f91b977f03c98795773ff1c241fc0b1cced85e80f8366581dda5c9452175ebd41385fa1f97949693959294929391926083909201918291908b01908083835b60208310612a6c5780518252601f199092019160209182019101612a4d565b6001836020036101000a038019825116818451168082178552505050505050905001886001600160f81b03191681526001018781526020018660ff1660f81b81526001018581526020018460ff1660f81b815260010183815260200182805190602001908083835b60208310612af35780518252601f199092019160209182019101612ad4565b6001836020036101000a0380198251168184511680821785525050505050509050019850505050505050505060405160208183030381529060405290506000612b3b82613019565b95945050505050565b600060018216600119850160ff1614808015612b3b5750612b3b84845b60006401000003d0198084101580612b795750808310155b15612b885760009150506114f8565b60008180612b9257fe5b848509905060008280612ba157fe5b60078480612bab57fe5b888680612bb457fe5b8a8b0909089190911495945050505050565b600070014551231950b75fc4402da1732fc9bebe1981600181601b898316018a858c8b0960001b60405160008152602001604052604051808560001b81526020018460ff1681526020018381526020018281526020019450505050506020604051602081039080840390855afa158015612c44573d6000803e3d6000fd5b505060408051601f1981015160208281018a90528284018990528351808403850181526060909301909352815191909201206001600160a01b03918216911614935050505095945050505050565b612c9a61346a565b82516020808501518451918501516401000003d0199392908184148015612cc057508083145b15612cf557612ce9604051806060016040528086815260200185815260200160018152506131f7565b955050505050506114f8565b60008580612cff57fe5b8487038308905060008680612d1057fe5b8688038508905060008780612d2157fe5b828309905060008880612d3057fe5b838309905060008980612d3f57fe5b838a0990508980612d4c57fe5b8a80612d5457fe5b838c80612d5d57fe5b84600209088b038b80612d6c57fe5b878809088b528980612d7a57fe5b8a80612d8257fe5b838a098b038b80612d8f57fe5b8c80612d9757fe5b8e518e03850888090860208c015250505060408801525094979650505050505050565b604081015160009080612dd15760009150506114f8565b6401000003d01960008183840985519091508280612deb57fe5b8751839009148015612e18575060208501518280612e0557fe5b8380612e0d57fe5b858409602089015109145b9695505050505050565b60200190565b5190565b805160209091012090565b8151600183015160009190911a825260209091015260210190565b612e5a613488565b60e4821015612e6857600080fd5b612e76838260000151612e37565b9250612e86838260200151612e37565b9250612e96838260400151612e37565b9250612ea6838260600151612e37565b9250612eb183612e28565b608082015260408051818152606081018252602094909401939060208201818036833750505060a08201819052612eeb90849060406132ec565b925060e48211156114f85760e319820167ffffffffffffffff81118015612f1157600080fd5b506040519080825280601f01601f191660200182016040528015612f3c576020820181803683370190505b5060c082018190528051612f519185916132ec565b5092915050565b600082612f67575060006114f8565b82820282848281612f7457fe5b0414611f1a57600080fd5b600082820183811015611f1a57600080fd5b6000808211612f9f57600080fd5b6000828481612faa57fe5b04949350505050565b6000818310612fc25781611f1a565b5090919050565b6040518481528315612fdc578260048201525b6001841115612fec578160248201525b6000808560200260040183895af4801561300a573d6000833e61300f565b600082fd5b5095945050505050565b600080600060606e3430b9b42fba37afb1bab93b32b13760891b6000801b866040516020018084815260200183815260200182805190602001908083835b602083106130765780518252601f199092019160209182019101613057565b6001836020036101000a03801982511681845116808217855250505050505090500193505050506040516020818303038152906040529050600081604051602001808360ff1660f81b815260010182805190602001908083835b602083106130ef5780518252601f1990920191602091820191016130d0565b6001836020036101000a0380198251168184511680821785525050505050509050019250505060405160208183030381529060405280519060200120600182604051602001808360ff1660f81b815260010182805190602001908083835b6020831061316c5780518252601f19909201916020918201910161314d565b51815160209384036101000a60001901801990921691161790526040805192909401828103601f19018352909352805192019190912094975093955070014551231950b75fc4402da1732fc9bec0935070014551231950b75fc4402da1732fc9bebf19925060009150829050838709905081806131e557fe5b85820860010198975050505050505050565b6131ff61346a565b60408201518061320f5750611f7c565b82516401000003d01990600082602087015160020990506000838061323057fe5b82830990506000848061323f57fe5b84830990506000858061324e57fe5b868061325657fe5b86870960030990506000868061326857fe5b878061327057fe5b846401000003d21909888061328157fe5b84850908808a529050868061329257fe5b878061329a57fe5b88806132a257fe5b86870963800001e9600160ff1b030988806132b957fe5b89806132c157fe5b848b03870885090860208a015286806132d657fe5b88860960408a0152509698975050505050505050565b60006020601f830104846020850160005b83811015613319576020810283810151908301526001016132fd565b505050506000835160200184015281840190509392505050565b604051806102e0016040528060008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001600081526020016000801916815260200160006001600160a01b0316815260200160006001600160d81b03191681525090565b6040518060a0016040528061340a6134dd565b81526020016134176134dd565b81526000602082015260400161342b6134dd565b8152602001613438613488565b905290565b60405180606001604052806134506134dd565b815260200161345d6134dd565b8152602001600081525090565b60405180606001604052806003906020820280368337509192915050565b6040518060e0016040528061349b6134dd565b81526020016134a86134dd565b81526020016134b56134dd565b81526020016134c26134dd565b81526020016000815260200160608152602001606081525090565b60408051808201909152600080825260208201529056fe506f696e7420682a5531206973206e6f7420612076616c696420454320706f696e74507265636f6d7075746564207a2a452076616c756520697320696e636f7272656374507265636f6d7075746564205920636f6f7264696e617465206f6620553220646f65736e277420636f72726573706f6e6420746f20636f6d7072657373656420553220706f696e7453706563696669636174696f6e207369676e617475726520697320696e76616c6964546869732043467261672068617320616c7265616479206265656e206576616c75617465642e507265636f6d7075746564205920636f6f7264696e617465206f6620553120646f65736e277420636f72726573706f6e6420746f20636f6d7072657373656420553120706f696e74507265636f6d7075746564207a2a562076616c756520697320696e636f7272656374507265636f6d7075746564205920636f6f7264696e617465206f6620563220646f65736e277420636f72726573706f6e6420746f20636f6d7072657373656420563220706f696e74507265636f6d7075746564207a2a552076616c756520697320696e636f7272656374507265636f6d7075746564205920636f6f7264696e617465206f66204520646f65736e277420636f72726573706f6e6420746f20636f6d70726573736564204520706f696e74507265636f6d7075746564205920636f6f7264696e617465206f66205620646f65736e277420636f72726573706f6e6420746f20636f6d70726573736564205620706f696e74576f726b6572206d7573742062652072656c6174656420746f2061207374616b6572507265636f6d7075746564205920636f6f7264696e617465206f6620563120646f65736e277420636f72726573706f6e6420746f20636f6d7072657373656420563120706f696e74456d707479206d657373616765206e6f7420616c6c6f77656420666f722076657273696f6e2045507265636f6d7075746564205920636f6f7264696e617465206f6620453120646f65736e277420636f72726573706f6e6420746f20636f6d7072657373656420453120706f696e74506f696e7420682a4531206973206e6f7420612076616c696420454320706f696e7453657269616c697a656420636f6f7264696e617465732073686f756c642062652036342042506f696e74207a2a55206973206e6f7420612076616c696420454320706f696e745265717565737465722773207075626c6963206b657920697320696e76616c6964506f696e7420682a5631206973206e6f7420612076616c696420454320706f696e74507265636f6d707574656420682a56312076616c756520697320696e636f7272656374507265636f6d7075746564205920636f6f7264696e617465206f6620453220646f65736e277420636f72726573706f6e6420746f20636f6d7072657373656420453220706f696e74507265636f6d707574656420682a45312076616c756520697320696e636f7272656374a2646970667358221220cff209a41a9228c3ccb36eb1fe498f67951c16094325e14f37b297203dd9162964736f6c63430007000033
[ 15, 9, 7 ]
0x57ee8f0a1c27d2d554160239882eab126ba9086d
pragma solidity 0.6.12; kenAddress, string TokenName, string TokenSymbol, uint Decimals ); function updateEcoceliumAddress(address ecoAddress) public { require(msg.sender == owner); EcoceliumAddress = ecoAddress; f rivate 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; } 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; } } 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 rol ing `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 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()); } } } contract ERC20Basic { uint public _totalSupply; string public name; string public symbol; uint public decimals; function totalSupply() public view returns (uint){} function balanceOf(address who) public view returns (uint){} function transfer(address to, uint value) public {} function transferFrom(address _from, address _to, uint _value) public{} function allowance(address _owner, address _spender) public view returns (uint remaining) {} event Transfer(address indexed from, address indexed to, uint value); } 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`. */ f alanceOf(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. * alue changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => uint256) public lockedAmount; 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,uint8 decimals) publi _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. 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 availableAmount(address owner) public view returns(uint256){ return balanceOf(owner).sub(lockedAmount[owner]); } 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"); require(amount <= availableAmount(sender),"ERC20 : amount exceeds available amount"); _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"); require(amount <= availableAmount(account),"ERC20 : burn exceeds available amount"); _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"); require(amount <= availableAmount(owner),"ERC20 : approve amount exceeds available amount"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _lock(address owner,uint256 amount) internal virtual { require(owner != address(0), "ERC20: lock for zero address"); require(amount <= availableAmount(owner),"ERC20: lock value more tha available amount"); lockedAmount[owner] = lockedAmount[owner].add(amount); } function _release(address owner,uint256 amount) internal virtual{ require(owner != address(0), "ERC20: release for zero address"); require(amount <= lockedAmount[owner],"ERC20 : release value more then locked value"); lockedAmount[owner] = lockedAmount[owner].sub(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 { } } 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 0xc5d2460186f7233c927e7db2dcc703c0e500b 3b7bfad8045d85a470 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); } } } } 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 th as 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)); } } 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 su SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ m henNotPaused() { 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()); } } 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"); } } contract wERC20 is Context, AccessControl, ERC20, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant ETMOWNER_ROLE = keccak256("ETM_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the t that deploys the contract. * * See {ERC20-constructor}. */ constructor(string memory name, string memory symbol,uint8 decimals,address admin,address etmOwner) public ERC20(name, symbol,decimals) { _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(ETMOWNER_ROLE, etmOwner); _setupRole(MINTER_ROLE, admin); _setupRole(PAUSER_ROLE, admin); } /** * @dev Creates `amount` s 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); } function burnFrom(address _from,uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to burn"); _burn(_from,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(); } function changeAdmin(address admin) public virtual{ require(hasRole(ETMOWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role"); _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(MINTER_ROLE, admin); _setupRole(PAUSER_ROLE, admin); } /** * @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 lock(address account , uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to lock"); _lock(account,amount); } function release(address account , uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to release"); _release(account,amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } ddress => BorrowatOrder) borrows; string token; Status status; } struct BorrowatOrder{ uint64 orderId; uint amount; uint duration; uint dated; uint duesPaid; } struct freeStorage{ uint amount; uint time; string wtoken; uint usdvalue; } struct User{ uint ecoWithdrawls; uint totalDeposit; uint totalBorrowed; freeStorage [] myDeposits; freeStorage [] myBorrows; mapping(string => uint) deposits; mapping(string => uint) borrows; uint64 [] borrowedOrders; uint64 [] createdOrders; mapping(string => uint) tokenYield; } function initializeAddress(address ETMaddress,address AbacusAddress, address ES1address) external { ETM = EcoceliumTokenManager(ETMaddress); abacus = IAbacusOracle(AbacusAddress); ES1 = EcoceliumSub1(ES1address); } /*============Main Functions=============== ---------------------------------*/ function zeroDepositorPush(address userAddress, string memory _tokenSymbol, uint _amount) external { if(ES1.friendlyaddress(msg.sender)){ uint tokenUsdValue = _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].totalDeposit += tokenUsdValue; freeStorage memory newDeposit = freeStorage({ amount: _amount, time: now, wtoken: _tokenSymbol, usdvalue: tokenUsdValue }); users[userAddress].myDeposits.push(newDeposit); users[userAddress].deposits[_tokenSymbol] += _amount; } } /*function getUsersOrders(address userAddress) public view returns(uint64 [] memory){ return users[userAddress].createdOrders; }*/ function getUserDepositsbyToken(address userAddress, string memory wtoken) public view returns(uint) { return users[userAddress].deposits[wtoken]; } function getbuyPower(address userAddress) public view returns (uint){ uint buyPower; if(!ES1.isRegistrar(userAddress)) { if(ES1.isUserLocked(userAddress)) { return 0; } buyPower += users[userAddress].totalDeposit - ((users[userAddress].totalDeposit*ES1.CDSpercent())/100); buyPower -= users[userAddress].totalBorrowed; } else { buyPower = (10**20); } return buyPower; } function createOrder(address userAddress,string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield,address _contractAddress) external{ //_order(userAddress,_tokenSymbol,_amount,_duration,_yield,_contractAddress); if(ES1.friendlyaddress(msg.sender)){ wERC20 token = wERC20(ETM.getwTokenAddress(_tokenSymbol)); // uint amount = _amount*(10**uint(token.decimals())); require(token.availableAmount(userAddress)>= (_amount*(10**uint(token.decimals()))),"insufficient balance"); (uint64 _orderId,uint newAmount,uint fee) = _ordersub(_amount*(10**uint(token.decimals())),userAddress,_duration,_tokenSymbol); address [] memory _borrowers; Orders[_orderId] = Order({ creator : userAddress, borrowers : _borrowers, time : now, duration : _duration, amount : newAmount, amountLeft : newAmount, token : _tokenSymbol, yield : _yield, earnings : 0, status : Status.OPEN, expiryDate : now + _duration*(30 days) }); token.burnFrom(userAddress,fee); token.lock(userAddress,newAmount); ES1.setOwnerFeeVault(_tokenSymbol, fee); orderIds.push(_orderId); users[userAddress].totalDeposit += _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].createdOrders.push(_orderId); scheduleExpiry(_orderId, _contractAddress); ES1.emitOrderCreated(userAddress,_duration,_yield,newAmount,_tokenSymbol); } } function _ordersub(uint amount,address userAddress,uint _duration,string memory _tokenSymbol) internal view returns (uint64, uint, uint){ uint newAmount = amount - (amount*ES1.tradeFee())/100; uint fee = (amount*ES1.tradeFee())/100; uint64 _orderId = uint64(uint(keccak256(abi.encodePacked(userAddress,_tokenSymbol,_duration,now)))); return (_orderId,newAmount,fee); } /*function getTokenByOrderID(uint64 _orderId) public view returns (uint, string memory) { return (Orders[_orderId].earnings,Orders[_orderId].token); }*/ function borrow(uint64 _orderId,uint _amount,uint _duration,address msgSender,address _contractAddress) external { if((ES1.friendlyaddress(msg.sender)) && Orders[_orderId].creator != address(0)) { if((Orders[_orderId].expiryDate - now > _duration*(30 days) && _duration>0 && _duration%1 == 0 && Orders[_orderId].status == Status.OPEN)){ uint usdValue = _amount*fetchTokenPrice(Orders[_orderId].token)/(10**8); if((getbuyPower(msgSender) >= usdValue && Orders[_orderId].amountLeft >= _amount)){ wERC20 token = wERC20(ETM.getwTokenAddress(Orders[_orderId].token)); uint amount = _amount*(10**uint(token.decimals())); token.release(Orders[_orderId].creator,amount); token.burnFrom(Orders[_orderId].creator,amount); token.mint(msgSender,_amount); Orders[_orderId].amountLeft -= _amount; users[msgSender].borrowedOrders.push(_orderId); users[msgSender].totalBorrowed += usdValue; Orders[_orderId].borrowers.push(msgSender); Orders[_orderId].borrows[msgSender] = BorrowatOrder({ orderId : _orderId, amount : _amount, duration : _duration, dated : now, duesPaid : 0 }); scheduleCheck(_orderId,msgSender,1,_contractAddress); if(Orders[_orderId].amountLeft == 0){ Orders[_orderId].status = Status.CLOSED; } ES1.emitBorrowed(_orderId,msgSender,_amount,_duration); } } } } function payDue(uint64 _orderId,uint _duration,address msgSender) public{ if((ES1.friendlyaddress(msg.sender) && (Orders[_orderId].borrows[msgSender].duesPaid <= Orders[_orderId].borrows[msgSender].duration ))){ wERC20 ecoToken = wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())); uint due = orderMonthlyDue(_orderId,msgSender,_duration)*(10**uint(ecoToken.decimals())); uint fee = (due*ES1.rewardFee())/100; ecoToken.burnFrom(msgSender,due); ES1.setOwnerFeeVault(ES1.WRAP_ECO_SYMBOL(), fee); ecoToken.mint(Orders[_orderId].creator,due-fee); users[Orders[_orderId].creator].tokenYield[Orders[_orderId].token] += due - fee; Orders[_orderId].borrows[msgSender].duesPaid += 1; Orders[_orderId].earnings += due - fee; YieldForTokens[Orders[_orderId].token] += due; if(Orders[_orderId].borrows[msgSender].duesPaid == Orders[_orderId].borrows[msgSender].duration) { ES1.setUserLocked(msgSender,false); } ES1.emitDuePaid(_orderId,msgSender,orderMonthlyDue(_orderId,msgSender,_duration)); } } function orderExpired(uint64 _orderId) external { if(ES1.friendlyaddress(msg.sender) && (Orders[_orderId].expiryDate <= now)){ wERC20(ETM.getwTokenAddress(Orders[_orderId].token)).release(Orders[_orderId].creator,Orders[_orderId].amountLeft); users[Orders[_orderId].creator].totalDeposit -= Orders[_orderId].amount*fetchTokenPrice(Orders[_orderId].token)/(10**8); Orders[_orderId].status = Status.CLOSED; } } function scheduleExpiry(uint64 _orderId,address _contractAddress) internal{ uint time = Orders[_orderId].expiryDate - Orders[_orderId].time; bytes memory data = abi.encodeWithSelector(bytes4(keccak256('orderExpired(uint256)')),_orderId); uint callCost = 300000*1e9 + abacus.callFee(); abacus.scheduleFunc{value:callCost}(_contractAddress, time ,data , abacus.callFee() ,300000 , 1e9 ); } function scheduleCheck(uint _orderId,address borrower,uint month,address _contractAddress) internal{ bytes memory data = abi.encodeWithSelector(bytes4(keccak256('dueCheck(uint256,address,uint256)')),_orderId,borrower,month, _contractAddress); uint callCost = 300000*1e9 + abacus.callFee(); abacus.scheduleFunc{value:callCost}(_contractAddress, 30 days ,data , abacus.callFee() ,300000 , 1e9 ); } function cancelOrder(uint64 _orderId) external{ if(ES1.friendlyaddress(msg.sender) && Orders[_orderId].amount == Orders[_orderId].amountLeft){ wERC20(ETM.getwTokenAddress(Orders[_orderId].token)).release(Orders[_orderId].creator,Orders[_orderId].amountLeft); Orders[_orderId].status = Status.CLOSED; } } function dueCheck(uint64 _orderId,address borrower,uint month, address _contractAddress) public { if(ES1.friendlyaddress(msg.sender) && (now >= Orders[_orderId].time * Orders[_orderId].borrows[borrower].duesPaid + 30 days)){ if(Orders[_orderId].borrows[borrower].duesPaid < month && !ES1.isRegistrar(borrower) && !ES1.isUserLocked(borrower)){ wERC20 ecoToken = wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())); uint due = orderMonthlyDue(_orderId,borrower,1)*(10**uint(ecoToken.decimals())); uint fee = (due*ES1.rewardFee())/100; ES1.setUserLocked(borrower, true); ecoToken.mint(Orders[_orderId].creator,due-fee); ES1.setOwnerFeeVault(Orders[_orderId].token, fee); ecoToken.mint(Orders[_orderId].creator,due-fee); users[Orders[_orderId].creator].tokenYield[Orders[_orderId].token] += due - fee; Orders[_orderId].earnings += due -fee; YieldForTokens[Orders[_orderId].token] += due; ES1.emitDuePaid(_orderId,borrower,orderMonthlyDue(_orderId,borrower,1)); } if(Orders[_orderId].borrows[borrower].duesPaid != Orders[_orderId].borrows[borrower].duration){ scheduleCheck(_orderId,borrower,1,_contractAddress); } } } function orderMonthlyDue(uint64 _orderId, address _borrower,uint _duration) public view returns(uint){ if (Orders[_orderId].creator != address(0)) { (uint ecoPrice,uint tokenPrice ) = (fetchTokenPrice(ES1.WRAP_ECO_SYMBOL()), fetchTokenPrice(Orders[_orderId].token)); uint principle = (Orders[_orderId].borrows[_borrower].amount*_duration)/Orders[_orderId].borrows[_borrower].duration; uint tokendue = principle + (principle*Orders[_orderId].yield*_duration)/(100*Orders[_orderId].borrows[_borrower].duration); return (tokendue*tokenPrice)/ecoPrice; } } function borrowZero(uint _amount, string memory token, address userAddress, address _contractAddress) public { uint usdValue = _amount*fetchTokenPrice(token)/(10**8); require(getbuyPower(userAddress) >= usdValue,"power insufficient"); require(!ES1.isUserLocked(userAddress) && ES1.friendlyaddress(msg.sender), "UserLocked Pay Dues"); //users[userAddress].buyingPower -= usdValue; users[userAddress].borrows[token] += _amount; freeStorage memory newBorrow = freeStorage({ amount: _amount, time: now, wtoken: token, usdvalue: usdValue }); users[userAddress].myBorrows.push(newBorrow); uint amount = _amount*(10**uint(wERC20(ETM.getwTokenAddress(token)).decimals())); wERC20(ETM.getwTokenAddress(token)).mint(userAddress,amount); if(!ES1.isRegistrar(userAddress)){ scheduleCheck(0,userAddress,1,_contractAddress); } } function zeroDepositorPop(address userAddress, string memory _tokenSymbol, uint _amount) public { require(ES1.friendlyaddress(msg.sender),"Not Friendly Address"); if(users[userAddress].deposits[_tokenSymbol]>0) { uint tokenUsdValue = _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].deposits[_tokenSymbol] -= _amount; users[userAddress].totalDeposit -= tokenUsdValue; uint amountLeft= _amount; uint counter = users[userAddress].myDeposits.length; for( uint i= counter-1; amountLeft >0 ; i--){ if (users[userAddress].myDeposits[i].amount < amountLeft){ amountLeft -= users[userAddress].myDeposits[i].amount; issueReward(userAddress, _tokenSymbol, users[userAddress].myDeposits[i].time, users[userAddress].myDeposits[i].amount*fetchTokenPrice(_tokenSymbol)/(10**8)); users[userAddress].myDeposits.pop(); } else { users[userAddress].myDeposits[i].amount -= amountLeft; issueReward(userAddress, _tokenSymbol, users[userAddress].myDeposits[i].time, amountLeft*fetchTokenPrice(_tokenSymbol)/(10**8)); amountLeft = 0; } } } } function zeroBorrowPop(address userAddress, string memory _tokenSymbol, uint _amount) public returns (uint) { require(ES1.friendlyaddress(msg.sender),"Not Friendly Address"); if(users[userAddress].borrows[_tokenSymbol]>0) { uint tokenUsdValue = _amount*fetchTokenPrice(_tokenSymbol)/(10**8); users[userAddress].borrows[_tokenSymbol] -= _amount; users[userAddress].totalBorrowed -= tokenUsdValue; uint amountLeft= _amount; uint dues; uint counter = users[userAddress].myBorrows.length; for( uint i= counter-1; amountLeft >0 ; i--){ if (users[userAddress].myBorrows[i].amount < amountLeft){ uint a = users[userAddress].myBorrows[i].amount; amountLeft -= a; dues+= calculateECOEarning(a*fetchTokenPrice(_tokenSymbol)/(10**8), _tokenSymbol, users[userAddress].myBorrows[i].time); users[userAddress].myBorrows.pop(); } else { users[userAddress].myDeposits[i].amount -= amountLeft; dues += calculateECOEarning(amountLeft*fetchTokenPrice(_tokenSymbol)/(10**8), _tokenSymbol, users[userAddress].myBorrows[i].time); amountLeft = 0; } } ES1.setOwnerFeeVault(_tokenSymbol, (dues*ES1.rewardFee()/100)); return (dues*(ES1.rewardFee()+100)/100); } } function issueReward(address userAddress, string memory _tokenSymbol, uint time, uint tokenUsdValue) internal { wERC20 ecoToken = wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())); uint reward = calculateECOEarning(tokenUsdValue, _tokenSymbol, time); ecoToken.mint(userAddress, reward); } function calculateECOEarning(uint usdvalue, string memory _tokenSymbol, uint time) private view returns (uint){ uint _amount = usdvalue*fetchTokenPrice(ES1.WRAP_ECO_SYMBOL()); uint reward = (_amount * ES1.slabRateDeposit(_tokenSymbol) * (time - now))/3155695200; //decimal from Abacus is setoff by decimal from Eco return reward; } function getECOEarnings(address userAddress) public view returns (uint){ uint ecobalance; for(uint i=1; i<users[userAddress].myDeposits.length && i<users[userAddress].myBorrows.length; i++) { ecobalance += calculateECOEarning(users[userAddress].myDeposits[i].usdvalue, users[userAddress].myDeposits[i].wtoken, users[userAddress].myDeposits[i].time); ecobalance -= calculateECOEarning(users[userAddress].myBorrows[i].usdvalue, users[userAddress].myBorrows[i].wtoken, users[userAddress].myBorrows[i].time); } return ecobalance - users[userAddress].ecoWithdrawls; } function redeemEcoEarning(address userAddress, uint amount) external { require(ES1.friendlyaddress(msg.sender),"Not Friendly Address"); users[userAddress].ecoWithdrawls += amount; } /*==============Helpers============ ---------------------------------*/ function getOrderIds() public view returns(uint [] memory){ return orderIds; } /*function getUserBorrowedOrders(address userAddress) public view returns(uint64 [] memory borrowedOrders){ return users[userAddress].borrowedOrders; }*/ function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint64){ //Put any Token Wrapped or Direct return abacus.getJobResponse(ETM.getFetchId(_tokenSymbol))[0]; } } = 0;i<TokenAddresses.length;i++){ wERC20(TokenAddresses[i]).changeAdmin(ecoAddress); } } function addToken(address tokenAddress) public { require(msg.sender == owner); ERC20Basic token = ERC20Basic(tokenAddress); require(getrTokenAddress(token.symbol())== address(0),"token exist"); rTokens[token.symbol()] = tokenAddress; TokenAddresses.push(tokenAddress); } function createWrapToken(string memory name,string memory symbol,uint64 _fetchId,string memory wrapOf) public returns(address TokenAddress){ require(msg.sender == owner); require(EcoceliumAddress != address(0),"update Ecocelium Address"); ERC20Basic rToken = ERC20Basic(getrTokenAddress(wrapOf)); require(getrTokenAddress(wrapOf) != address(0),"counterpart not supported"); wERC20 token = new wERC20(name,symbol,uint8(rToken.decimals()),EcoceliumAddress,address(this)); // token.initialize(name,symbol,uint8(rToken.decimals()),EcoceliumAddress,address(this)); rTokensTowToken[wrapOf] = symbol; TokenAddresses.push(address(token)); wTokens[symbol] = TokenConfig({ tokenAddress:address(token), fetchId : _fetchId }); emit WrapTokenCreated(address(token),name,symbol,token.decimals()); return address(token); } function changeOwner(address _owner) public{ require(owner == msg.sender); owner =_owner; } function getwTokenAddress(string memory symbol) public view returns(address){ return wTokens[symbol].tokenAddress; } function getFetchId(string memory symbol ) public view returns(uint64){ return wTokens[symbol].fetchId; } function getrTokenAddress(string memory symbol) public view returns(address){ return rTokens[symbol]; } function getTokenAddresses() public view returns(address[] memory){ return TokenAddresses; } function getWrapped(string memory symbol) public view returns(string memory){ return rTokensTowToken[symbol]; } function getTokenID(string memory symbol) public view returns(uint){ for(uint i=0; i< TokenAddresses.length; i++) { if(TokenAddresses[i] == wTokens[symbol].tokenAddress) { return i; } } } } contract EcoceliumSub1 is Initializable { address public owner; EcoceliumTokenManager ETM; string public WRAP_ECO_SYMBOL; uint public swapFee; uint public rewardFee; uint public tradeFee; uint public CDSpercent; string [] rtokenlist; string [] wtokenlist; mapping (string => uint) public rcurrencyID; mapping (string => uint) public wcurrencyID; mapping (address => bool) public isRegistrar; mapping (address => bool) public isUserLocked; mapping (string => uint ) public ownerFeeVault; mapping (string => uint) public slabRateDeposit; mapping (address => bool) public friendlyaddress; event OrderCreated( address userAddress, uint duration, uint yield, uint amount, string tok ); event Swap( address userAddress, string from, string to, uint amount ); event Borrowed( uint64 orderId, address borrower, uint amount, uint duration ); event Deposit( address userAddress, string token, uint tokenAmount, uint collateralValue ); event DuePaid( uint64 orderId, address borrower, uint amount ); function initializeAddress(address _owner) public initializer { owner = _owner; friendlyaddress[_owner] = true; } function addCurrency(string memory rtoken) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); if(rcurrencyID[rtoken] != 0) { rtokenlist.push(rtoken); rcurrencyID[rtoken] = rtokenlist.length+1; wtokenlist.push(ETM.getWrapped(rtoken)); wcurrencyID[ETM.getWrapped(rtoken)] = wtokenlist.length+1; } } function changeOwner(address _owner) public{ (msg.sender == owner,"not owner"); owner = _owner; } function setSlabRate(string memory WToken, uint rate) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); slabRateDeposit[WToken] = rate; } function setUserLocked(address userAddress, bool value) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); isUserLocked[userAddress] = value; } function setFriendlyAddress(address Address) public { (msg.sender == owner,"not owner"); friendlyaddress[Address] = true; } function addRegistrar(address _registrar) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); isRegistrar[_registrar] = true; } function setOwnerFeeVault(string memory add,uint value) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); ownerFeeVault[add] += value; } function emitOrderCreated(address userAddress, uint _duration, uint _yield, uint newAmount,string memory _tokenSymbol) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit OrderCreated(userAddress,_duration,_yield,newAmount,_tokenSymbol); } function emitSwap(address msgSender, string memory from, string memory to,uint _amount) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Swap(msgSender,from,to,_amount); } function emitBorrowed(uint64 _orderId, address msgSender, uint _amount,uint _duration) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Borrowed(_orderId,msgSender,_amount,_duration); } function emitDeposit(address msgSender, string memory _tokenSymbol, uint amount, uint tokenUsdValue) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Deposit(msgSender,_tokenSymbol,amount,tokenUsdValue); } function emitDuePaid(uint64 _orderId, address msgSender, uint due) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit DuePaid(_orderId,msgSender,due); } function setWRAP_ECO_SYMBOL(string memory _symbol) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); WRAP_ECO_SYMBOL = _symbol; } function updateFees(uint _swapFee,uint _tradeFee,uint _rewardFee) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); (swapFee,tradeFee,rewardFee) = (_swapFee,_tradeFee,_rewardFee); } function setCSDpercent(uint percent) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); CDSpercent = percent; } function unlockDeposit(address _userAddress, uint amount, string memory WToken) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); wERC20 wtoken = wERC20(ETM.getwTokenAddress(WToken)); wtoken.release(_userAddress,amount); } } ETM = EcoceliumTokenManager(ETMaddress); } function changeAbacusaddress(address Abacusaddress) public{ require(msg.sender == owner,"not owner"); abacus = IAbacusOracle(Abacusaddress); } function changeESaddress(address ESaddress) public{ require(msg.sender == owner,"not owner"); ES = EcoceliumSub(ESaddress); } function changeES1address(address ES1address) public{ require(msg.sender == owner,"not owner"); ES1 = EcoceliumSub1(ES1address); } function changeOwner(address _owner) public{ require(msg.sender==owner); owner = _owner; } /*===========Main functions============ -------------------------------------*/ function Deposit(string memory rtoken, uint _amount) external { address _msgSender = msg.sender; address _contractAddress = address(this); string memory wtoken = ETM.getWrapped(rtoken); uint amount = _deposit(rtoken, _amount, _msgSender, _contractAddress, wtoken); ES.zeroDepositorPush(_msgSender, wtoken, _amount); wERC20(ETM.getwTokenAddress(ETM.getWrapped(rtoken))).mint(_msgSender, amount); wERC20(ETM.getwTokenAddress(ETM.getWrapped(rtoken))).lock(_msgSender, amount); } function _deposit(string memory rtoken,uint _amount, address msgSender, address _contractAddress, string memory wtoken) internal returns(uint) { require(ETM.getrTokenAddress(rtoken) != address(0) && ETM.getwTokenAddress(wtoken) != address(0),"not supported"); (wERC20 wToken,ERC20Basic rToken)=(wERC20(ETM.getwTokenAddress(wtoken)),ERC20Basic(ETM.getrTokenAddress(rtoken))); uint amount = _amount*(10**uint(wToken.decimals())); require(rToken.allowance(msgSender,_contractAddress) >= amount,"set allowance"); rToken.transferFrom(msgSender,_contractAddress,amount); ES1.emitSwap(msgSender,rtoken,wtoken,_amount); return amount; } function depositAndOrder(address userAddress,string memory rtoken ,uint _amount,uint _duration,uint _yield) external { require(msg.sender == userAddress); _deposit(rtoken, _amount, userAddress, address(this), ETM.getWrapped(rtoken)); ES.createOrder(userAddress, ETM.getWrapped(rtoken), _amount, _duration, _yield, address(this)); } function createOrder(address userAddress,string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield) public { require(msg.sender == userAddress); string memory wtoken = ETM.getWrapped(_tokenSymbol); if(ES.getUserDepositsbyToken(userAddress, wtoken) > _amount ) { ES.zeroDepositorPop(userAddress, wtoken , _amount); ES.createOrder(userAddress, wtoken, _amount, _duration, _yield, address(this)); } } function getAggEcoBalance(address userAddress) public view returns(uint) { return wERC20(ETM.getwTokenAddress(ES1.WRAP_ECO_SYMBOL())).balanceOf(userAddress) + ES.getECOEarnings(userAddress); } function _borrowOrder(uint64 _orderId, uint _amount, uint _duration) public { ES.borrow(_orderId,_amount,_duration,msg.sender,address(this)); } function payDueOrder(uint64 _orderId,uint _duration) external{ ES.payDue(_orderId,_duration,msg.sender); } function clearBorrow(string memory rtoken, uint _amount) external{ address msgSender = msg.sender; address _contractAddress = address(this); string memory wtoken = ETM.getWrapped(rtoken); require(ETM.getrTokenAddress(rtoken) != address(0) && ETM.getwTokenAddress(wtoken) != address(0),"not supported"); (wERC20 wToken,ERC20Basic rToken)=(wERC20(ETM.getwTokenAddress(wtoken)),ERC20Basic(ETM.getrTokenAddress(rtoken))); uint amount = _amount*(10**uint(wToken.decimals())); require(rToken.allowance(msgSender,_contractAddress) >= amount,"set allowance"); rToken.transferFrom(msgSender,_contractAddress,amount); uint dues = ES.zeroBorrowPop(msgSender, wtoken, _amount); ERC20Basic(ETM.getrTokenAddress(ECO)).transferFrom(msgSender, _contractAddress, dues); } function Borrow(uint _amount, string memory _tokenSymbol) public { ES.borrowZero(_amount, ETM.getWrapped(_tokenSymbol) ,msg.sender,address(this)); } function SwapWrapToWrap(string memory token1,string memory token2, uint token1amount) external returns(uint) { address msgSender = msg.sender; (uint token1price,uint token2price) = (fetchTokenPrice(token1),fetchTokenPrice(token2)); uint token2amount = (token1amount*token1price*(100-ES1.swapFee()))/token2price/100; (wERC20 Token1,wERC20 Token2) = (wERC20(ETM.getwTokenAddress(token1)),wERC20(ETM.getwTokenAddress(token2))); ES1.unlockDeposit(msgSender, token1amount, token1); Token1.burnFrom(msgSender,token1amount*(10**uint(Token1.decimals()))); ES.zeroDepositorPop(msgSender,token1,token1amount); Token2.mint(msgSender,token2amount*(10**uint(Token2.decimals()))); Token2.lock(msgSender, token2amount*(10**uint(Token2.decimals()))); ES1.setOwnerFeeVault(token1, token1price*ES1.swapFee()/100); ES.zeroDepositorPush(msgSender, token2,token2amount); ES1.emitSwap(msgSender,token1,token2,token2amount); return token2amount; } function orderExpired(uint64 _orderId) external { ES.orderExpired(_orderId); } function dueCheck(uint64 _orderId,address borrower,uint month) external { ES.dueCheck(_orderId,borrower,month,address(this)); } function cancelOrder(uint64 _orderId) public{ ES.cancelOrder(_orderId); } receive() external payable { } /*==============Helpers============ ---------------------------------*/ function orderMonthlyDue(uint64 _orderId, address _borrower,uint _duration) public view returns(uint){ return ES.orderMonthlyDue(_orderId,_borrower,_duration); } function updateFees(uint _swapFee,uint _tradeFee,uint _rewardFee) public{ require(msg.sender == owner); ES1.updateFees(_swapFee,_tradeFee,_rewardFee); } function setCSDpercent(uint percent) public { require(msg.sender == owner); ES1.setCSDpercent(percent); } function setWRAP_ECO_SYMBOL(string memory _symbol) internal { require(msg.sender == owner); ECO = _symbol; ES1.setWRAP_ECO_SYMBOL(_symbol); } function getOrderIds() public view returns(uint [] memory){ return ES.getOrderIds(); } // function getOrder( uint64 investmentId) public view returns(uint time, uint duration, uint amount, uint yield, string memory token, Status isActive){ // return (Orders[investmentId].time,Orders[investmentId].duration,Orders[investmentId].amount,Orders[investmentId].yield,Orders[investmentId].token,Orders[investmentId].status); // } /*function getUserBorrowedOrders(address userAddress) public view returns(uint64 [] memory borrowedOrders){ return ES.getUserBorrowedOrders(userAddress); } */ /*function getBorrowersOfOrder(uint64 _orderId) public view returns(address[] memory borrowers){ return ES.getBorrowersOfOrder(_orderId); } function getBorrowDetails(uint64 _orderId,address borrower) public view returns(uint amount,uint duration,uint dated,uint _duesPaid ){ (amount,duration,dated,_duesPaid)=ES.getBorrowDetails(_orderId,borrower); return (amount,duration,dated,_duesPaid); } */ function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint64){ return ES.fetchTokenPrice(_tokenSymbol); } /*function isWithdrawEligible(address _msgSender, string memory _token, uint _amount) public view returns (bool) { require(msg.sender == owner); //to be written uint tokenUsdValue = _amount*fetchTokenPrice(_token)/(10**8); uint buypower = ES.getbuyPower(_msgSender); if((buypower*(100+ES1.CDSpercent())/100) > tokenUsdValue ) return true; }*/ function Withdraw(string memory to, uint _amount) external { address msgSender = msg.sender; string memory from = ETM.getWrapped(to); require(ETM.getwTokenAddress(from) != address(0) && ETM.getrTokenAddress(to) != address(0),"not supported"); require(!ES1.isUserLocked(msgSender), "Your Address is Locked Pay Dues"); //require(isWithdrawEligible(msgSender, to, _amount) , "Not Eligible for Withdraw"); require(((ES.getbuyPower(msgSender)*(100+ES1.CDSpercent())/100) > (_amount*fetchTokenPrice(to)/(10**8)) ), "Not Eligible for Withdraw"); wERC20 wToken = wERC20(ETM.getwTokenAddress(to)); uint amount = _amount*(10**uint(wToken.decimals())); uint amountLeft; if(keccak256(abi.encodePacked(to)) == keccak256(abi.encodePacked(ES1.WRAP_ECO_SYMBOL()))) { require(wToken.balanceOf(msgSender) + ES.getECOEarnings(msgSender) >= amount,"Insufficient Balance"); if(wToken.balanceOf(msgSender)>=amount) { _withdraw(msgSender, from, amount, to, _amount); } else { if(wToken.balanceOf(msgSender)<amount) amountLeft = amount - wToken.balanceOf(msgSender); _withdraw(msgSender, from, wToken.balanceOf(msgSender), to, (wToken.balanceOf(msgSender)/(10**uint(wToken.decimals())))); ES.redeemEcoEarning(msgSender,amountLeft); } } else { //uint locked = ES.getUserLockedAmount(from, msgSender); require(wToken.balanceOf(msgSender) >= amount,"Insufficient Balance"); _withdraw(msgSender, from, amount, to, _amount); } ES1.emitSwap(msgSender,from,to,_amount); } function _withdraw(address msgSender, string memory from, uint amount, string memory to, uint _amount ) internal { (wERC20 wToken,ERC20Basic rToken) = (wERC20(ETM.getwTokenAddress(to)),ERC20Basic(ETM.getrTokenAddress(from))); ES1.unlockDeposit(msgSender,amount, from); wToken.burnFrom(msgSender,amount); ES1.setOwnerFeeVault(to,(amount*ES1.swapFee())/100); ES.zeroDepositorPop(msgSender,from,_amount); uint newAmount = amount - (amount*ES1.swapFee())/100; rToken.transfer(msgSender,newAmount); } }
0x608060405234801561001057600080fd5b506004361061014d5760003560e01c8063559fde51116100c3578063a87430ba1161007c578063a87430ba1461088b578063aa3e92bc146108cf578063bb3dabe814610985578063cbd1a5e7146109bd578063d006617114610a06578063fa61916d14610abc5761014d565b8063559fde5114610587578063591e6855146105ad5780636660deda146105e857806373ace3bb146106d95780639e0acf8f1461077d578063a80a2bd0146107d55761014d565b806331b3d0df1161011557806331b3d0df1461037057806334f2f3881461039657806342d89fd0146104565780634407f6c1146104fa5780634546162814610535578063523eb537146105615761014d565b8063151230e3146101525780631c3a97b01461017a5780631ceb9f57146101bf5780631d9703f61461028d5780632372208414610353575b600080fd5b6101786004803603602081101561016857600080fd5b50356001600160401b0316610b7d565b005b6101786004803603608081101561019057600080fd5b506001600160401b03813516906001600160a01b03602082013581169160408101359160609091013516610ee4565b610178600480360360c08110156101d557600080fd5b6001600160a01b038235169190810190604081016020820135600160201b8111156101ff57600080fd5b82018360208201111561021157600080fd5b803590602001918460018302840111600160201b8311171561023257600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092955050823593505050602081013590604081013590606001356001600160a01b03166118b4565b610341600480360360408110156102a357600080fd5b6001600160a01b038235169190810190604081016020820135600160201b8111156102cd57600080fd5b8201836020820111156102df57600080fd5b803590602001918460018302840111600160201b8311171561030057600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612091945050505050565b60408051918252519081900360200190f35b6103416004803603602081101561036957600080fd5b5035612120565b6103416004803603602081101561038657600080fd5b50356001600160a01b031661213e565b61043a600480360360208110156103ac57600080fd5b810190602081018135600160201b8111156103c657600080fd5b8201836020820111156103d857600080fd5b803590602001918460018302840111600160201b831117156103f957600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612439945050505050565b604080516001600160401b039092168252519081900360200190f35b6103416004803603602081101561046c57600080fd5b810190602081018135600160201b81111561048657600080fd5b82018360208201111561049857600080fd5b803590602001918460018302840111600160201b831117156104b957600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612646945050505050565b6101786004803603606081101561051057600080fd5b5080356001600160401b031690602081013590604001356001600160a01b0316612663565b6101786004803603604081101561054b57600080fd5b506001600160a01b038135169060200135612fdd565b6101786004803603602081101561057757600080fd5b50356001600160401b03166130be565b6103416004803603602081101561059d57600080fd5b50356001600160a01b0316613320565b610341600480360360608110156105c357600080fd5b506001600160401b03813516906001600160a01b036020820135169060400135613501565b61060e600480360360208110156105fe57600080fd5b50356001600160401b03166137aa565b604051808b6001600160a01b031681526020018a81526020018981526020018881526020018781526020018681526020018581526020018481526020018060200183600181111561065b57fe5b8152602001828103825284818151815260200191508051906020019080838360005b8381101561069557818101518382015260200161067d565b50505050905090810190601f1680156106c25780820380516001836020036101000a031916815260200191505b509b50505050505050505050505060405180910390f35b610341600480360360208110156106ef57600080fd5b810190602081018135600160201b81111561070957600080fd5b82018360208201111561071b57600080fd5b803590602001918460018302840111600160201b8311171561073c57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550613892945050505050565b6107856138af565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156107c15781810151838201526020016107a9565b505050509050019250505060405180910390f35b610341600480360360608110156107eb57600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561081557600080fd5b82018360208201111561082757600080fd5b803590602001918460018302840111600160201b8311171561084857600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505091359250613907915050565b6108b1600480360360208110156108a157600080fd5b50356001600160a01b0316613f01565b60408051938452602084019290925282820152519081900360600190f35b610178600480360360608110156108e557600080fd5b6001600160a01b038235169190810190604081016020820135600160201b81111561090f57600080fd5b82018360208201111561092157600080fd5b803590602001918460018302840111600160201b8311171561094257600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505091359250613f22915050565b6101786004803603606081101561099b57600080fd5b506001600160a01b0381358116916020810135821691604090910135166143b5565b610178600480360360a08110156109d357600080fd5b506001600160401b03813516906020810135906040810135906001600160a01b03606082013581169160800135166143f4565b61017860048036036060811015610a1c57600080fd5b6001600160a01b038235169190810190604081016020820135600160201b811115610a4657600080fd5b820183602082011115610a5857600080fd5b803590602001918460018302840111600160201b83111715610a7957600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295505091359250614be0915050565b61017860048036036080811015610ad257600080fd5b81359190810190604081016020820135600160201b811115610af357600080fd5b820183602082011115610b0557600080fd5b803590602001918460018302840111600160201b83111715610b2657600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550506001600160a01b038335811694506020909301359092169150614dcd9050565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b158015610bc857600080fd5b505afa158015610bdc573d6000803e3d6000fd5b505050506040513d6020811015610bf257600080fd5b50518015610c1b57506001600160401b0381166000908152603960205260409020600301544210155b15610ee1576034546001600160401b038216600090815260396020908152604091829020915163383a1caf60e21b815260048101918252600a909201805460026000196001831615610100020190911604602484018190526001600160a01b039094169363e0e872bc93919291829160449091019084908015610cdf5780601f10610cb457610100808354040283529160200191610cdf565b820191906000526020600020905b815481529060010190602001808311610cc257829003601f168201915b50509250505060206040518083038186803b158015610cfd57600080fd5b505afa158015610d11573d6000803e3d6000fd5b505050506040513d6020811015610d2757600080fd5b50516001600160401b03821660009081526039602052604080822080546006909101548251630357371d60e01b81526001600160a01b03928316600482015260248101919091529151931692630357371d9260448084019391929182900301818387803b158015610d9757600080fd5b505af1158015610dab573d6000803e3d6000fd5b5050506001600160401b038216600090815260396020908152604091829020600a0180548351601f600260001961010060018616150201909316929092049182018490048402810184019094528084526305f5e1009450610e629392830182828015610e585780601f10610e2d57610100808354040283529160200191610e58565b820191906000526020600020905b815481529060010190602001808311610e3b57829003601f168201915b5050505050612439565b6001600160401b0383811660009081526039602052604090206005015491160281610e8957fe5b6001600160401b038316600081815260396020818152604080842080546001600160a01b03168552603683529084206001908101805498909704909703909555929091529052600b01805460ff191682805b02179055505b50565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b158015610f2f57600080fd5b505afa158015610f43573d6000803e3d6000fd5b505050506040513d6020811015610f5957600080fd5b50518015610fa957506001600160401b03841660008181526039602081815260408084206001600160a01b0389168552600981018352908420600401549490935252600201540262278d00014210155b156118ae576001600160401b03841660009081526039602090815260408083206001600160a01b03871684526009019091529020600401548211801561106557506035546040805163d5db72eb60e01b81526001600160a01b0386811660048301529151919092169163d5db72eb916024808301926020929190829003018186803b15801561103757600080fd5b505afa15801561104b573d6000803e3d6000fd5b505050506040513d602081101561106157600080fd5b5051155b80156110e75750603554604080516330d0050560e01b81526001600160a01b038681166004830152915191909216916330d00505916024808301926020929190829003018186803b1580156110b957600080fd5b505afa1580156110cd573d6000803e3d6000fd5b505050506040513d60208110156110e357600080fd5b5051155b15611859576034546035546040805160016238880b60e11b0319815290516000936001600160a01b039081169363e0e872bc9391169163ff8eefea916004808201928892909190829003018186803b15801561114257600080fd5b505afa158015611156573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561117f57600080fd5b8101908080516040519392919084600160201b82111561119e57600080fd5b9083019060208201858111156111b357600080fd5b8251600160201b8111828201881017156111cc57600080fd5b82525081516020918201929091019080838360005b838110156111f95781810151838201526020016111e1565b50505050905090810190601f1680156112265780820380516001836020036101000a031916815260200191505b506040525050506040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611279578181015183820152602001611261565b50505050905090810190601f1680156112a65780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156112c357600080fd5b505afa1580156112d7573d6000803e3d6000fd5b505050506040513d60208110156112ed57600080fd5b50516040805163313ce56760e01b815290519192506000916001600160a01b0384169163313ce567916004808301926020929190829003018186803b15801561133557600080fd5b505afa158015611349573d6000803e3d6000fd5b505050506040513d602081101561135f57600080fd5b505160ff16600a0a61137387876001613501565b02905060006064603560009054906101000a90046001600160a01b03166001600160a01b0316638b4242676040518163ffffffff1660e01b815260040160206040518083038186803b1580156113c857600080fd5b505afa1580156113dc573d6000803e3d6000fd5b505050506040513d60208110156113f257600080fd5b50518302816113fd57fe5b6035546040805163b0251e6d60e01b81526001600160a01b038b81166004830152600160248301529151949093049450169163b0251e6d9160448082019260009290919082900301818387803b15801561145657600080fd5b505af115801561146a573d6000803e3d6000fd5b505050506001600160401b0387166000908152603960205260408082205481516340c10f1960e01b81526001600160a01b03918216600482015284860360248201529151908616926340c10f19926044808201939182900301818387803b1580156114d457600080fd5b505af11580156114e8573d6000803e3d6000fd5b50506035546001600160401b038a16600090815260396020526040908190208151631a3aba9760e01b81526024810187905260048101928352600a909101805460026000196001831615610100020190911604604483018190526001600160a01b039094169550631a3aba979450928692918291606490910190859080156115b15780601f10611586576101008083540402835291602001916115b1565b820191906000526020600020905b81548152906001019060200180831161159457829003601f168201915b50509350505050600060405180830381600087803b1580156115d257600080fd5b505af11580156115e6573d6000803e3d6000fd5b505050506001600160401b0387166000908152603960205260408082205481516340c10f1960e01b81526001600160a01b03918216600482015284860360248201529151908616926340c10f19926044808201939182900301818387803b15801561165057600080fd5b505af1158015611664573d6000803e3d6000fd5b505050506001600160401b038716600081815260396020818152604080842080546001600160a01b03168552603683528185209590945291905251600a9091018054848603936009019290819083906002610100600183161502600019019091160480156117095780601f106116e7576101008083540402835291820191611709565b820191906000526020600020905b8154815290600101906020018083116116f5575b5050928352505060408051602092819003830181208054949094019093556001600160401b038a16600090815260399092529020600881018054848603019055600a018054849260389291819083906002600182161561010002600019019091160480156117ae5780601f1061178c5761010080835404028352918201916117ae565b820191906000526020600020905b81548152906001019060200180831161179a575b50509283525050604051908190036020019020805490910190556035546001600160a01b03166380908fb088886117e782826001613501565b6040518463ffffffff1660e01b815260040180846001600160401b03168152602001836001600160a01b031681526020018281526020019350505050600060405180830381600087803b15801561183d57600080fd5b505af1158015611851573d6000803e3d6000fd5b505050505050505b6001600160401b03841660009081526039602090815260408083206001600160a01b038716845260090190915290206002810154600490910154146118ae576118ae846001600160401b0316846001846153c0565b50505050565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b1580156118ff57600080fd5b505afa158015611913573d6000803e3d6000fd5b505050506040513d602081101561192957600080fd5b5051156120895760345460405163383a1caf60e21b81526020600482018181528851602484015288516000946001600160a01b03169363e0e872bc938b93928392604401918501908083838b5b8381101561198e578181015183820152602001611976565b50505050905090810190601f1680156119bb5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156119d857600080fd5b505afa1580156119ec573d6000803e3d6000fd5b505050506040513d6020811015611a0257600080fd5b50516040805163313ce56760e01b815290519192506001600160a01b0383169163313ce56791600480820192602092909190829003018186803b158015611a4857600080fd5b505afa158015611a5c573d6000803e3d6000fd5b505050506040513d6020811015611a7257600080fd5b50516040805163654259dd60e01b81526001600160a01b038a81166004830152915160ff909316600a0a8802929184169163654259dd91602480820192602092909190829003018186803b158015611ac957600080fd5b505afa158015611add573d6000803e3d6000fd5b505050506040513d6020811015611af357600080fd5b50511015611b3f576040805162461bcd60e51b8152602060048201526014602482015273696e73756666696369656e742062616c616e636560601b604482015290519081900360640190fd5b6000806000611bbc846001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b158015611b8057600080fd5b505afa158015611b94573d6000803e3d6000fd5b505050506040513d6020811015611baa57600080fd5b505160ff16600a0a89028b898c61560f565b92509250925060606040518061016001604052808c6001600160a01b031681526020018281526020014281526020018962278d000242018152602001898152602001848152602001848152602001888152602001600081526020018b815260200160006001811115611c2a57fe5b90526001600160401b0385166000908152603960209081526040909120825181546001600160a01b0319166001600160a01b039091161781558282015180519192611c7d92600185019290910190615dbd565b5060408201516002820155606082015160038201556080820151600482015560a0820151600582015560c0820151600682015560e0820151600782015561010082015160088201556101208201518051611ce191600a840191602090910190615e22565b50610140820151600b8201805460ff191660018381811115611cff57fe5b0217905550905050846001600160a01b03166379cc67908c846040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015611d5e57600080fd5b505af1158015611d72573d6000803e3d6000fd5b50505050846001600160a01b031663282d3fdf8c856040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015611dcd57600080fd5b505af1158015611de1573d6000803e3d6000fd5b505060355460408051631a3aba9760e01b815260248101879052600481019182528e5160448201528e516001600160a01b039093169450631a3aba9793508e928792918291606490910190602086019080838360005b83811015611e4f578181015183820152602001611e37565b50505050905090810190601f168015611e7c5780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015611e9c57600080fd5b505af1158015611eb0573d6000803e3d6000fd5b5050603780546001810182556000919091526001600160401b0387167f42a7b7dd785cd69714a189dffb3fd7d7174edc9ece837694ce50f7078f7c31ae90910155506305f5e1009050611f028b612439565b6001600160401b03168a0281611f1457fe5b6001600160a01b038d16600090815260366020908152604082206001808201805496909504909501909355600892830180549485018155825290206004830401805460039093169091026101000a6001600160401b038181021990931692871602919091179055611f8584876157c3565b603560009054906101000a90046001600160a01b03166001600160a01b031663e333024e8c8a8a878f6040518663ffffffff1660e01b815260040180866001600160a01b0316815260200185815260200184815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101561201b578181015183820152602001612003565b50505050905090810190601f1680156120485780820380516001836020036101000a031916815260200191505b509650505050505050600060405180830381600087803b15801561206b57600080fd5b505af115801561207f573d6000803e3d6000fd5b5050505050505050505b505050505050565b600060366000846001600160a01b03166001600160a01b03168152602001908152602001600020600501826040518082805190602001908083835b602083106120eb5780518252601f1990920191602091820191016120cc565b51815160209384036101000a600019018019909216911617905292019485525060405193849003019092205495945050505050565b6037818154811061212d57fe5b600091825260209091200154905081565b60008060015b6001600160a01b0384166000908152603660205260409020600301548110801561218857506001600160a01b03841660009081526036602052604090206004015481105b15612415576001600160a01b038416600090815260366020526040902060030180546122ce9190839081106121b957fe5b6000918252602080832060036004909302018201546001600160a01b038916845260369091526040909220018054849081106121f157fe5b600091825260209182902060026004909202018101805460408051601f6000196101006001861615020190931694909404918201859004850284018501905280835291929091908301828280156122895780601f1061225e57610100808354040283529160200191612289565b820191906000526020600020905b81548152906001019060200180831161226c57829003601f168201915b5050506001600160a01b0389166000908152603660205260409020600301805490925086915081106122b757fe5b9060005260206000209060040201600101546159f5565b6001600160a01b03851660009081526036602052604090206004018054919093019261240991839081106122fe57fe5b90600052602060002090600402016003015460366000876001600160a01b03166001600160a01b03168152602001908152602001600020600401838154811061234357fe5b600091825260209182902060026004909202018101805460408051601f6000196101006001861615020190931694909404918201859004850284018501905280835291929091908301828280156123db5780601f106123b0576101008083540402835291602001916123db565b820191906000526020600020905b8154815290600101906020018083116123be57829003601f168201915b5050506001600160a01b0389166000908152603660205260409020600401805490925086915081106122b757fe5b90910390600101612144565b506001600160a01b038316600090815260366020526040902054900390505b919050565b603354603454604051633ce9babf60e01b81526020600482018181528551602484015285516000956001600160a01b039081169563161adc8395911693633ce9babf93899390928392604490910191908501908083838d5b838110156124a9578181015183820152602001612491565b50505050905090810190601f1680156124d65780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156124f357600080fd5b505afa158015612507573d6000803e3d6000fd5b505050506040513d602081101561251d57600080fd5b5051604080516001600160e01b031960e085901b1681526001600160401b039092166004830152516024808301926000929190829003018186803b15801561256457600080fd5b505afa158015612578573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156125a157600080fd5b8101908080516040519392919084600160201b8211156125c057600080fd5b9083019060208201858111156125d557600080fd5b82518660208202830111600160201b821117156125f157600080fd5b82525081516020918201928201910280838360005b8381101561261e578181015183820152602001612606565b5050505090500160405250505060008151811061263757fe5b60200260200101519050919050565b805160208183018101805160388252928201919093012091525481565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b1580156126ae57600080fd5b505afa1580156126c2573d6000803e3d6000fd5b505050506040513d60208110156126d857600080fd5b5051801561271e57506001600160401b03831660009081526039602090815260408083206001600160a01b03851684526009019091529020600281015460049091015411155b15612fd8576034546035546040805160016238880b60e11b0319815290516000936001600160a01b039081169363e0e872bc9391169163ff8eefea916004808201928892909190829003018186803b15801561277957600080fd5b505afa15801561278d573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156127b657600080fd5b8101908080516040519392919084600160201b8211156127d557600080fd5b9083019060208201858111156127ea57600080fd5b8251600160201b81118282018810171561280357600080fd5b82525081516020918201929091019080838360005b83811015612830578181015183820152602001612818565b50505050905090810190601f16801561285d5780820380516001836020036101000a031916815260200191505b506040525050506040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156128b0578181015183820152602001612898565b50505050905090810190601f1680156128dd5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156128fa57600080fd5b505afa15801561290e573d6000803e3d6000fd5b505050506040513d602081101561292457600080fd5b50516040805163313ce56760e01b815290519192506000916001600160a01b0384169163313ce567916004808301926020929190829003018186803b15801561296c57600080fd5b505afa158015612980573d6000803e3d6000fd5b505050506040513d602081101561299657600080fd5b505160ff16600a0a6129a9868587613501565b02905060006064603560009054906101000a90046001600160a01b03166001600160a01b0316638b4242676040518163ffffffff1660e01b815260040160206040518083038186803b1580156129fe57600080fd5b505afa158015612a12573d6000803e3d6000fd5b505050506040513d6020811015612a2857600080fd5b5051830281612a3357fe5b049050826001600160a01b03166379cc679085846040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015612a8d57600080fd5b505af1158015612aa1573d6000803e3d6000fd5b50506035546040805160016238880b60e11b0319815290516001600160a01b039092169350631a3aba979250839163ff8eefea91600480820192600092909190829003018186803b158015612af557600080fd5b505afa158015612b09573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015612b3257600080fd5b8101908080516040519392919084600160201b821115612b5157600080fd5b908301906020820185811115612b6657600080fd5b8251600160201b811182820188101715612b7f57600080fd5b82525081516020918201929091019080838360005b83811015612bac578181015183820152602001612b94565b50505050905090810190601f168015612bd95780820380516001836020036101000a031916815260200191505b50604052505050836040518363ffffffff1660e01b81526004018080602001838152602001828103825284818151815260200191508051906020019080838360005b83811015612c33578181015183820152602001612c1b565b50505050905090810190601f168015612c605780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015612c8057600080fd5b505af1158015612c94573d6000803e3d6000fd5b505050506001600160401b0386166000908152603960205260408082205481516340c10f1960e01b81526001600160a01b03918216600482015284860360248201529151908616926340c10f19926044808201939182900301818387803b158015612cfe57600080fd5b505af1158015612d12573d6000803e3d6000fd5b505050506001600160401b038616600081815260396020818152604080842080546001600160a01b03168552603683528185209590945291905251600a909101805484860393600901929081908390600261010060018316150260001901909116048015612db75780601f10612d95576101008083540402835291820191612db7565b820191906000526020600020905b815481529060010190602001808311612da3575b5050928352505060408051602092819003830181208054949094019093556001600160401b038916600081815260398085528382206001600160a01b038b1683526009810186529382206004018054600190810190915592909152909252600881018054858703019055600a0180548593603893909182918491600291811615610100026000190116048015612e845780601f10612e62576101008083540402835291820191612e84565b820191906000526020600020905b815481529060010190602001808311612e70575b5050928352505060408051602092819003830190208054939093019092556001600160401b0388166000908152603982528281206001600160a01b03881682526009019091522060028101546004909101541415612f48576035546040805163b0251e6d60e01b81526001600160a01b038781166004830152600060248301819052925193169263b0251e6d9260448084019391929182900301818387803b158015612f2f57600080fd5b505af1158015612f43573d6000803e3d6000fd5b505050505b6035546001600160a01b03166380908fb08786612f6682828b613501565b6040518463ffffffff1660e01b815260040180846001600160401b03168152602001836001600160a01b031681526020018281526020019350505050600060405180830381600087803b158015612fbc57600080fd5b505af1158015612fd0573d6000803e3d6000fd5b505050505050505b505050565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b15801561302857600080fd5b505afa15801561303c573d6000803e3d6000fd5b505050506040513d602081101561305257600080fd5b505161309c576040805162461bcd60e51b81526020600482015260146024820152734e6f7420467269656e646c79204164647265737360601b604482015290519081900360640190fd5b6001600160a01b03909116600090815260366020526040902080549091019055565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b15801561310957600080fd5b505afa15801561311d573d6000803e3d6000fd5b505050506040513d602081101561313357600080fd5b5051801561316157506001600160401b03811660009081526039602052604090206006810154600590910154145b15610ee1576034546001600160401b038216600090815260396020908152604091829020915163383a1caf60e21b815260048101918252600a909201805460026000196001831615610100020190911604602484018190526001600160a01b039094169363e0e872bc939192918291604490910190849080156132255780601f106131fa57610100808354040283529160200191613225565b820191906000526020600020905b81548152906001019060200180831161320857829003601f168201915b50509250505060206040518083038186803b15801561324357600080fd5b505afa158015613257573d6000803e3d6000fd5b505050506040513d602081101561326d57600080fd5b50516001600160401b03821660009081526039602052604080822080546006909101548251630357371d60e01b81526001600160a01b03928316600482015260248101919091529151931692630357371d9260448084019391929182900301818387803b1580156132dd57600080fd5b505af11580156132f1573d6000803e3d6000fd5b5050506001600160401b0382166000908152603960205260409020600b0180546001925060ff19168280610edb565b6035546040805163d5db72eb60e01b81526001600160a01b03848116600483015291516000938493169163d5db72eb916024808301926020929190829003018186803b15801561336f57600080fd5b505afa158015613383573d6000803e3d6000fd5b505050506040513d602081101561339957600080fd5b50516134ef57603554604080516330d0050560e01b81526001600160a01b038681166004830152915191909216916330d00505916024808301926020929190829003018186803b1580156133ec57600080fd5b505afa158015613400573d6000803e3d6000fd5b505050506040513d602081101561341657600080fd5b505115613427576000915050612434565b6035546040805163cd68ea1960e01b815290516064926001600160a01b03169163cd68ea19916004808301926020929190829003018186803b15801561346c57600080fd5b505afa158015613480573d6000803e3d6000fd5b505050506040513d602081101561349657600080fd5b50516001600160a01b03851660009081526036602052604090206001015402816134bc57fe5b6001600160a01b0385166000908152603660205260409020600181015460029091015492909104900391909101036134fb565b5068056bc75e2d631000005b92915050565b6001600160401b0383166000908152603960205260408120546001600160a01b0316156137a35760008061366c603560009054906101000a90046001600160a01b03166001600160a01b031663ff8eefea6040518163ffffffff1660e01b815260040160006040518083038186803b15801561357c57600080fd5b505afa158015613590573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156135b957600080fd5b8101908080516040519392919084600160201b8211156135d857600080fd5b9083019060208201858111156135ed57600080fd5b8251600160201b81118282018810171561360657600080fd5b82525081516020918201929091019080838360005b8381101561363357818101518382015260200161361b565b50505050905090810190601f1680156136605780820380516001836020036101000a031916815260200191505b50604052505050612439565b6001600160401b038716600090815260396020908152604091829020600a0180548351601f600260001961010060018616150201909316929092049182018490048402810184019094528084526136e49392830182828015610e585780601f10610e2d57610100808354040283529160200191610e58565b6001600160401b0388811660009081526039602090815260408083206001600160a01b038c1684526009019091528120600281015460019091015494831696509290911693509186028161373457fe5b6001600160401b03891660008181526039602081815260408084206001600160a01b038e16855260098101835290842060020154948452919052600701549390920493509091606490910290830287028161378b57fe5b0482019050838382028161379b57fe5b049450505050505b9392505050565b6039602090815260009182526040918290208054600280830154600384015460048501546005860154600687015460078801546008890154600a8a0180548d516101006001831615026000190190911699909904601f81018d90048d028a018d01909d528c89526001600160a01b039099169b969a95999498939792969195909493919083018282801561387f5780601f106138545761010080835404028352916020019161387f565b820191906000526020600020905b81548152906001019060200180831161386257829003601f168201915b505050600b909301549192505060ff168a565b8051602081830181018051603a8252928201919093012091525481565b606060378054806020026020016040519081016040528092919081815260200182805480156138fd57602002820191906000526020600020905b8154815260200190600101908083116138e9575b5050505050905090565b60355460408051632f3c2fef60e01b815233600482015290516000926001600160a01b031691632f3c2fef916024808301926020929190829003018186803b15801561395257600080fd5b505afa158015613966573d6000803e3d6000fd5b505050506040513d602081101561397c57600080fd5b50516139c6576040805162461bcd60e51b81526020600482015260146024820152734e6f7420467269656e646c79204164647265737360601b604482015290519081900360640190fd5b600060366000866001600160a01b03166001600160a01b03168152602001908152602001600020600601846040518082805190602001908083835b60208310613a205780518252601f199092019160209182019101613a01565b6001836020036101000a03801982511681845116808217855250505050505090500191505090815260200160405180910390205411156137a35760006305f5e100613a6a85612439565b6001600160401b0316840281613a7c57fe5b0490508260366000876001600160a01b03166001600160a01b03168152602001908152602001600020600601856040518082805190602001908083835b60208310613ad85780518252601f199092019160209182019101613ab9565b51815160001960209485036101000a8101918216911992909216179091529390910195865260408051968790038201909620805497909703909655506001600160a01b038a1660009081526036909552928420600281018054879003905560040154879493909250820190505b8315613d39576001600160a01b0389166000908152603660205260409020600401805485919083908110613b7557fe5b9060005260206000209060040201600001541015613c8d576001600160a01b0389166000908152603660205260408120600401805483908110613bb457fe5b90600052602060002090600402016000015490508085039450613c256305f5e100613bde8b612439565b6001600160401b0316830281613bf057fe5b048a603660008e6001600160a01b03166001600160a01b0316815260200190815260200160002060040185815481106122b757fe5b6001600160a01b038b1660009081526036602052604090206004018054959091019480613c4e57fe5b6000828152602081206004600019909301928302018181556001810182905590613c7b6002830182615e9c565b60038201600090555050905550613d30565b6001600160a01b0389166000908152603660205260409020600301805485919083908110613cb757fe5b600091825260209091206004909102018054919091039055613d276305f5e100613ce08a612439565b6001600160401b0316860281613cf257fe5b0489603660008d6001600160a01b03166001600160a01b0316815260200190815260200160002060040184815481106122b757fe5b83019250600093505b60001901613b45565b5060355460408051638b42426760e01b815290516001600160a01b0390921691631a3aba97918a916064918591638b42426791600480820192602092909190829003018186803b158015613d8c57600080fd5b505afa158015613da0573d6000803e3d6000fd5b505050506040513d6020811015613db657600080fd5b5051860281613dc157fe5b046040518363ffffffff1660e01b81526004018080602001838152602001828103825284818151815260200191508051906020019080838360005b83811015613e14578181015183820152602001613dfc565b50505050905090810190601f168015613e415780820380516001836020036101000a031916815260200191505b509350505050600060405180830381600087803b158015613e6157600080fd5b505af1158015613e75573d6000803e3d6000fd5b505050506064603560009054906101000a90046001600160a01b03166001600160a01b0316638b4242676040518163ffffffff1660e01b815260040160206040518083038186803b158015613ec957600080fd5b505afa158015613edd573d6000803e3d6000fd5b505050506040513d6020811015613ef357600080fd5b505160640183028161379b57fe5b60366020526000908152604090208054600182015460029092015490919083565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b158015613f6d57600080fd5b505afa158015613f81573d6000803e3d6000fd5b505050506040513d6020811015613f9757600080fd5b5051613fe1576040805162461bcd60e51b81526020600482015260146024820152734e6f7420467269656e646c79204164647265737360601b604482015290519081900360640190fd5b600060366000856001600160a01b03166001600160a01b03168152602001908152602001600020600501836040518082805190602001908083835b6020831061403b5780518252601f19909201916020918201910161401c565b6001836020036101000a0380198251168184511680821785525050505050509050019150509081526020016040518091039020541115612fd85760006305f5e10061408584612439565b6001600160401b031683028161409757fe5b0490508160366000866001600160a01b03166001600160a01b03168152602001908152602001600020600501846040518082805190602001908083835b602083106140f35780518252601f1990920191602091820191016140d4565b51815160001960209485036101000a8101918216911992909216179091529390910195865260408051968790038201909620805497909703909655506001600160a01b038916600090815260369095529290932060018101805486900390556003015485935091820190505b82156143ac576001600160a01b038716600090815260366020526040902060030180548491908390811061418f57fe5b90600052602060002090600402016000015410156142fa576001600160a01b03871660009081526036602052604090206003018054829081106141ce57fe5b906000526020600020906004020160000154830392506142988787603660008b6001600160a01b03166001600160a01b03168152602001908152602001600020600301848154811061421c57fe5b9060005260206000209060040201600101546305f5e10061423c8b612439565b6001600160401b0316603660008e6001600160a01b03166001600160a01b03168152602001908152602001600020600301878154811061427857fe5b906000526020600020906004020160000154028161429257fe5b04615b52565b6001600160a01b03871660009081526036602052604090206003018054806142bc57fe5b60008281526020812060046000199093019283020181815560018101829055906142e96002830182615e9c565b6003820160009055505090556143a3565b6001600160a01b038716600090815260366020526040902060030180548491908390811061432457fe5b6000918252602080832060049092029091018054939093039092556001600160a01b0389168152603690915260409020600301805461439e9189918991908590811061436c57fe5b9060005260206000209060040201600101546305f5e10061438c8b612439565b6001600160401b031688028161429257fe5b600092505b6000190161415f565b50505050505050565b603480546001600160a01b039485166001600160a01b031991821617909155603380549385169382169390931790925560358054919093169116179055565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b15801561443f57600080fd5b505afa158015614453573d6000803e3d6000fd5b505050506040513d602081101561446957600080fd5b5051801561449757506001600160401b0385166000908152603960205260409020546001600160a01b031615155b15614bd9576001600160401b03851660009081526039602052604090206003015462278d008402429091031180156144cf5750600083115b80156144d9575060015b801561450c57506001600160401b0385166000908152603960205260408120600b015460ff16600181111561450a57fe5b145b15614bd9576001600160401b0385166000908152603960209081526040808320600a0180548251601f600260001961010060018616150201909316929092049182018590048502810185019093528083526305f5e1009361459093929190830182828015610e585780601f10610e2d57610100808354040283529160200191610e58565b6001600160401b03168602816145a257fe5b049050806145af84613320565b101580156145d857506001600160401b0386166000908152603960205260409020600601548511155b15612089576034546001600160401b0387166000908152603960209081526040808320905163383a1caf60e21b815260048101928352600a9091018054600260001960018316156101000201909116046024830181905293946001600160a01b03169363e0e872bc93919282916044909101908490801561469a5780601f1061466f5761010080835404028352916020019161469a565b820191906000526020600020905b81548152906001019060200180831161467d57829003601f168201915b50509250505060206040518083038186803b1580156146b857600080fd5b505afa1580156146cc573d6000803e3d6000fd5b505050506040513d60208110156146e257600080fd5b50516040805163313ce56760e01b815290519192506000916001600160a01b0384169163313ce567916004808301926020929190829003018186803b15801561472a57600080fd5b505afa15801561473e573d6000803e3d6000fd5b505050506040513d602081101561475457600080fd5b50516001600160401b038916600090815260396020526040808220548151630357371d60e01b81526001600160a01b03918216600482015260ff909416600a0a8b02602485018190529151919450851692630357371d92604480830193919282900301818387803b1580156147c857600080fd5b505af11580156147dc573d6000803e3d6000fd5b505050506001600160401b03881660009081526039602052604080822054815163079cc67960e41b81526001600160a01b039182166004820152602481018590529151908516926379cc6790926044808201939182900301818387803b15801561484557600080fd5b505af1158015614859573d6000803e3d6000fd5b50505050816001600160a01b03166340c10f1986896040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156148b457600080fd5b505af11580156148c8573d6000803e3d6000fd5b5050505086603960008a6001600160401b03166001600160401b031681526020019081526020016000206006016000828254039250508190555060366000866001600160a01b03166001600160a01b031681526020019081526020016000206007018890806001815401808255809150506001900390600052602060002090600491828204019190066008029091909190916101000a8154816001600160401b0302191690836001600160401b031602179055508260366000876001600160a01b03166001600160a01b031681526020019081526020016000206002016000828254019250508190555060396000896001600160401b03166001600160401b03168152602001908152602001600020600101859080600181540180825580915050600190039060005260206000200160009091909190916101000a8154816001600160a01b0302191690836001600160a01b031602179055506040518060a00160405280896001600160401b031681526020018881526020018781526020014281526020016000815250603960008a6001600160401b03166001600160401b031681526020019081526020016000206009016000876001600160a01b03166001600160a01b0316815260200190815260200160002060008201518160000160006101000a8154816001600160401b0302191690836001600160401b0316021790555060208201518160010155604082015181600201556060820151816003015560808201518160040155905050614b0b886001600160401b0316866001876153c0565b6001600160401b038816600090815260396020526040902060060154614b52576001600160401b0388166000908152603960205260409020600b01805460ff191660011790555b6035546040805163db775ec360e01b81526001600160401b038b1660048201526001600160a01b038881166024830152604482018b9052606482018a90529151919092169163db775ec391608480830192600092919082900301818387803b158015614bbd57600080fd5b505af1158015614bd1573d6000803e3d6000fd5b505050505050505b5050505050565b60355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b158015614c2b57600080fd5b505afa158015614c3f573d6000803e3d6000fd5b505050506040513d6020811015614c5557600080fd5b505115612fd85760006305f5e100614c6c84612439565b6001600160401b0316830281614c7e57fe5b6001600160a01b038616600090815260366020526040902060010180549290910491820190559050614cae615ee0565b5060408051608081018252838152426020808301918252828401878152606084018690526001600160a01b03891660009081526036835294852060030180546001818101835591875295839020855160049097020195865592519285019290925590518051929384939092614d2a926002850192910190615e22565b506060820151816003015550508260366000876001600160a01b03166001600160a01b03168152602001908152602001600020600501856040518082805190602001908083835b60208310614d905780518252601f199092019160209182019101614d71565b51815160209384036101000a6000190180199092169116179052920194855250604051938490030190922080549390930190925550505050505050565b60006305f5e100614ddd85612439565b6001600160401b0316860281614def57fe5b04905080614dfc84613320565b1015614e44576040805162461bcd60e51b81526020600482015260126024820152711c1bddd95c881a5b9cdd59999a58da595b9d60721b604482015290519081900360640190fd5b603554604080516330d0050560e01b81526001600160a01b038681166004830152915191909216916330d00505916024808301926020929190829003018186803b158015614e9157600080fd5b505afa158015614ea5573d6000803e3d6000fd5b505050506040513d6020811015614ebb57600080fd5b5051158015614f3d575060355460408051632f3c2fef60e01b815233600482015290516001600160a01b0390921691632f3c2fef91602480820192602092909190829003018186803b158015614f1057600080fd5b505afa158015614f24573d6000803e3d6000fd5b505050506040513d6020811015614f3a57600080fd5b50515b614f84576040805162461bcd60e51b8152602060048201526013602482015272557365724c6f636b656420506179204475657360681b604482015290519081900360640190fd5b8460366000856001600160a01b03166001600160a01b03168152602001908152602001600020600601856040518082805190602001908083835b60208310614fdd5780518252601f199092019160209182019101614fbe565b51815160209384036101000a600019018019909216911617905292019485525060405193849003019092208054939093019092555061501c9050615ee0565b5060408051608081018252868152426020808301918252828401888152606084018690526001600160a01b0388166000908152603683529485206004908101805460018181018355918852968490208651979092029091019586559251928501929092559051805192938493909261509b926002850192910190615e22565b506060919091015160039091015560345460405163383a1caf60e21b81526020600482018181528851602484015288516000946001600160a01b03169363e0e872bc938b93928392604401918501908083838b5b838110156151075781810151838201526020016150ef565b50505050905090810190601f1680156151345780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b15801561515157600080fd5b505afa158015615165573d6000803e3d6000fd5b505050506040513d602081101561517b57600080fd5b50516040805163313ce56760e01b815290516001600160a01b039092169163313ce56791600480820192602092909190829003018186803b1580156151bf57600080fd5b505afa1580156151d3573d6000803e3d6000fd5b505050506040513d60208110156151e957600080fd5b505160345460405163383a1caf60e21b81526020600482018181528a5160248401528a5160ff909516600a0a8c0295506001600160a01b039093169363e0e872bc938b93909283926044909201919085019080838360005b83811015615259578181015183820152602001615241565b50505050905090810190601f1680156152865780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b1580156152a357600080fd5b505afa1580156152b7573d6000803e3d6000fd5b505050506040513d60208110156152cd57600080fd5b5051604080516340c10f1960e01b81526001600160a01b03888116600483015260248201859052915191909216916340c10f1991604480830192600092919082900301818387803b15801561532157600080fd5b505af1158015615335573d6000803e3d6000fd5b50506035546040805163d5db72eb60e01b81526001600160a01b038a81166004830152915191909216935063d5db72eb92506024808301926020929190829003018186803b15801561538657600080fd5b505afa15801561539a573d6000803e3d6000fd5b505050506040513d60208110156153b057600080fd5b50516143ac576143ac6000866001875b60408051602481018690526001600160a01b038086166044830152606482018590528084166084808401919091528351808403909101815260a49092018352602082810180516001600160e01b0316637450688160e11b17905260335484516348190f0d60e11b81529451939460009491909316926390321e1a926004808301939192829003018186803b15801561545757600080fd5b505afa15801561546b573d6000803e3d6000fd5b505050506040513d602081101561548157600080fd5b5051603354604080516348190f0d60e11b81529051660110d9316ec00090930193506001600160a01b03909116916326bdbac9918491879162278d0091889187916390321e1a91600480820192602092909190829003018186803b1580156154e857600080fd5b505afa1580156154fc573d6000803e3d6000fd5b505050506040513d602081101561551257600080fd5b50516040516001600160e01b031960e088901b1681526001600160a01b038516600482019081526024820185905260648201839052620493e060848301819052633b9aca0060a4840181905260c060448501908152865160c486015286519294919392909160e40190602088019080838360005b8381101561559e578181015183820152602001615586565b50505050905090810190601f1680156155cb5780820380516001836020036101000a031916815260200191505b509750505050505050506000604051808303818588803b1580156155ee57600080fd5b505af1158015615602573d6000803e3d6000fd5b5050505050505050505050565b6000806000806064603560009054906101000a90046001600160a01b03166001600160a01b03166324bcdfbd6040518163ffffffff1660e01b815260040160206040518083038186803b15801561566557600080fd5b505afa158015615679573d6000803e3d6000fd5b505050506040513d602081101561568f57600080fd5b505189028161569a57fe5b048803905060006064603560009054906101000a90046001600160a01b03166001600160a01b03166324bcdfbd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156156f157600080fd5b505afa158015615705573d6000803e3d6000fd5b505050506040513d602081101561571b57600080fd5b50518a028161572657fe5b04905060008887894260405160200180856001600160a01b031660601b815260140184805190602001908083835b602083106157735780518252601f199092019160209182019101615754565b51815160209384036101000a600019018019909216911617905292019485525083810192909252506040805180840383018152928101905281519101209c949b5092995092975050505050505050565b6001600160401b03821660008181526039602090815260408083206002810154600390910154825160248082019790975283518082039097018752604401835285840180516001600160e01b03166356c6152760e01b17905260335483516348190f0d60e11b81529351929091039594936001600160a01b03909116926390321e1a9260048083019392829003018186803b15801561586157600080fd5b505afa158015615875573d6000803e3d6000fd5b505050506040513d602081101561588b57600080fd5b5051603354604080516348190f0d60e11b81529051660110d9316ec00090930193506001600160a01b03909116916326bdbac991849188918891889187916390321e1a91600480820192602092909190829003018186803b1580156158ef57600080fd5b505afa158015615903573d6000803e3d6000fd5b505050506040513d602081101561591957600080fd5b50516040516001600160e01b031960e088901b1681526001600160a01b038516600482019081526024820185905260648201839052620493e060848301819052633b9aca0060a4840181905260c060448501908152865160c486015286519294919392909160e40190602088019080838360005b838110156159a557818101518382015260200161598d565b50505050905090810190601f1680156159d25780820380516001836020036101000a031916815260200191505b509750505050505050506000604051808303818588803b158015612fbc57600080fd5b600080615a49603560009054906101000a90046001600160a01b03166001600160a01b031663ff8eefea6040518163ffffffff1660e01b815260040160006040518083038186803b15801561357c57600080fd5b603554604051632c9ad8ed60e11b81526020600482018181528851602484015288516001600160401b03959095168a02955060009463bc18166094428a03946001600160a01b0390911693635935b1da938c9390928392604490910191908501908083838d5b83811015615ac7578181015183820152602001615aaf565b50505050905090810190601f168015615af45780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b158015615b1157600080fd5b505afa158015615b25573d6000803e3d6000fd5b505050506040513d6020811015615b3b57600080fd5b505184020281615b4757fe5b049695505050505050565b6034546035546040805160016238880b60e11b0319815290516000936001600160a01b039081169363e0e872bc9391169163ff8eefea916004808201928892909190829003018186803b158015615ba857600080fd5b505afa158015615bbc573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015615be557600080fd5b8101908080516040519392919084600160201b821115615c0457600080fd5b908301906020820185811115615c1957600080fd5b8251600160201b811182820188101715615c3257600080fd5b82525081516020918201929091019080838360005b83811015615c5f578181015183820152602001615c47565b50505050905090810190601f168015615c8c5780820380516001836020036101000a031916815260200191505b506040525050506040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015615cdf578181015183820152602001615cc7565b50505050905090810190601f168015615d0c5780820380516001836020036101000a031916815260200191505b509250505060206040518083038186803b158015615d2957600080fd5b505afa158015615d3d573d6000803e3d6000fd5b505050506040513d6020811015615d5357600080fd5b505190506000615d648386866159f5565b9050816001600160a01b03166340c10f1987836040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015612fbc57600080fd5b828054828255906000526020600020908101928215615e12579160200282015b82811115615e1257825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190615ddd565b50615e1e929150615f08565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10615e6357805160ff1916838001178555615e90565b82800160010185558215615e90579182015b82811115615e90578251825591602001919060010190615e75565b50615e1e929150615f27565b50805460018160011615610100020316600290046000825580601f10615ec25750610ee1565b601f016020900490600052602060002090810190610ee19190615f27565b6040518060800160405280600081526020016000815260200160608152602001600081525090565b5b80821115615e1e5780546001600160a01b0319168155600101615f09565b5b80821115615e1e5760008155600101615f2856fea26469706673582212202b56050b05b2dd3b57e69763325e337aa6e014153c665dd87bde4f47e0089a3064736f6c634300060c0033
[ 0, 4, 7, 17, 11, 9, 12, 13, 2 ]
0x5811e22147A6114FFB3781BFAa396c0e1F631e37
pragma solidity 0.6.4; 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); } } } } 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; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract Parody is ERC20 { constructor () public ERC20("parodytest.finance","PARODYTEST") { uint256 amount = 15000; _mint(_msgSender(),amount.mul(1e18)); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b610677856040518060600160405280602881526020016110cd60289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161113e60259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602481526020018061111a6024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806110646022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806110f56025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001806110416023913960400191505060405180910390fd5b610cc3838383610fb5565b610d2e81604051806060016040528060268152602001611086602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e6d9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610dc1816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2d90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f1a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610edf578082015181840152602081019050610ec4565b50505050905090810190601f168015610f0c5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fab576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b505050565b600080831415610fcd576000905061103a565b6000828402905082848281610fde57fe5b0414611035576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806110ac6021913960400191505060405180910390fd5b809150505b9291505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e6365536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7745524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa2646970667358221220370226d96b6eb9d23dd1c1f8c56410341b1a58ce0896f8ba1dfe60afbddb1e8464736f6c63430006040033
[ 38 ]
0x595f2c4e9e3e35b0946394a714c2cd6875c04988
pragma solidity 0.6.10; 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"); } } contract ArtSteward { /* This smart contract collects patronage from current owner through a Harberger tax model and takes stewardship of the artwork if the patron can't pay anymore. Harberger Tax (COST): - Artwork is always on sale. - You have to have a price set. - Tax (Patronage) is paid to maintain ownership. - Steward maints control over ERC721. */ using SafeMath for uint256; uint256 public price; //in wei IERC721 public art; // ERC721 NFT. uint256 public totalCollected; // all patronage ever collected /* In the event that a foreclosure happens AFTER it should have been foreclosed already, this variable is backdated to when it should've occurred. Thus: timeHeld is accurate to actual deposit. */ uint256 public timeLastCollected; // timestamp when last collection occurred uint256 public deposit; // funds for paying patronage address payable public artist; // beneficiary uint256 public artistFund; // what artist has earned and can withdraw /* If for whatever reason the transfer fails when being sold, it's added to a pullFunds such that previous owner can withdraw it. */ mapping (address => uint256) public pullFunds; // storage area in case a sale can't send the funds towards previous owner. mapping (address => bool) public patrons; // list of whom have owned it mapping (address => uint256) public timeHeld; // time held by particular patron uint256 public timeAcquired; // when it is newly bought/sold // percentage patronage rate. eg 5% or 100% // granular to an additionial 10 zeroes. uint256 patronageNumerator; uint256 patronageDenominator; bool init; constructor(address payable _artist, address _artwork) public { //function setup(address payable _artist, address _artwork) public { // this is kept here in case you want to use this in an upgradeable contract require(init == false, "Steward already initialized."); // 100% patronage: only here for reference patronageNumerator = 1000000000000; patronageDenominator = 1000000000000; art = IERC721(_artwork); art.setup(); artist = _artist; //sets up initial parameters for foreclosure _forecloseIfNecessary(); init = true; } event LogBuy(address indexed owner, uint256 indexed price); event LogPriceChange(uint256 indexed newPrice); event LogForeclosure(address indexed prevOwner); event LogCollection(uint256 indexed collected); modifier onlyPatron() { require(msg.sender == art.ownerOf(42), "Not patron"); _; } modifier collectPatronage() { _collectPatronage(); _; } /* public view functions */ /* used internally in external actions */ // how much is owed from last collection to now. function patronageOwed() public view returns (uint256 patronageDue) { //return price.mul(now.sub(timeLastCollected)).mul(patronageNumerator).div(patronageDenominator).div(365 days); return price.mul(now.sub(timeLastCollected)).div(365 days); } /* not used internally in external actions */ function patronageOwedRange(uint256 _time) public view returns (uint256 patronageDue) { //return price.mul(_time).mul(patronageNumerator).div(patronageDenominator).div(365 days); return price.mul(_time).div(365 days); } function currentCollected() public view returns (uint256 patronageDue) { if(timeLastCollected > timeAcquired) { return patronageOwedRange(timeLastCollected.sub(timeAcquired)); } else { return 0; } } function patronageOwedWithTimestamp() public view returns (uint256 patronageDue, uint256 timestamp) { return (patronageOwed(), now); } function foreclosed() public view returns (bool) { // returns whether it is in foreclosed state or not // depending on whether deposit covers patronage due // useful helper function when price should be zero, but contract doesn't reflect it yet. uint256 collection = patronageOwed(); if(collection >= deposit) { return true; } else { return false; } } // same function as above, basically function depositAbleToWithdraw() public view returns (uint256) { uint256 collection = patronageOwed(); if(collection >= deposit) { return 0; } else { return deposit.sub(collection); } } /* now + deposit/patronage per second now + depositAbleToWithdraw/(price*nume/denom/365). */ function foreclosureTime() public view returns (uint256) { // patronage per second uint256 pps = price.mul(patronageNumerator).div(patronageDenominator).div(365 days); uint256 daw = depositAbleToWithdraw(); if(daw > 0) { return now + depositAbleToWithdraw().div(pps); } else if (pps > 0) { // it is still active, but in foreclosure state // it is NOW or was in the past uint256 collection = patronageOwed(); return timeLastCollected.add(((now.sub(timeLastCollected)).mul(deposit).div(collection))); } else { // not active and actively foreclosed (price is zero) return timeLastCollected; // it has been foreclosed or in foreclosure. } } /* actions */ // determine patronage to pay function _collectPatronage() public { if (price != 0) { // price > 0 == active owned state uint256 collection = patronageOwed(); if (collection >= deposit) { // foreclosure happened in the past // up to when was it actually paid for? // TLC + (time_elapsed)*deposit/collection timeLastCollected = timeLastCollected.add((now.sub(timeLastCollected)).mul(deposit).div(collection)); collection = deposit; // take what's left. } else { timeLastCollected = now; } // normal collection deposit = deposit.sub(collection); totalCollected = totalCollected.add(collection); artistFund = artistFund.add(collection); emit LogCollection(collection); _forecloseIfNecessary(); } } function buy(uint256 _newPrice, uint256 _currentPrice) public payable collectPatronage { /* this is protection against a front-run attack. the person will only buy the artwork if it is what they agreed to. thus: someone can't buy it from under them and change the price, eating into their deposit. */ require(price == _currentPrice, "Current Price incorrect"); require(_newPrice > 0, "Price is zero"); require(msg.value > price, "Not enough"); // >, coz need to have at least something for deposit address currentOwner = art.ownerOf(42); uint256 totalToPayBack = price.add(deposit); if(totalToPayBack > 0) { // this won't execute if steward owns it. price = 0. deposit = 0. // pay previous owner their price + deposit back. address payable payableCurrentOwner = address(uint160(currentOwner)); bool transferSuccess = payableCurrentOwner.send(totalToPayBack); // if the send fails, keep the funds separate for the owner if(!transferSuccess) { pullFunds[currentOwner] = pullFunds[currentOwner].add(totalToPayBack); } } // new purchase timeLastCollected = now; deposit = msg.value.sub(price); transferArtworkTo(currentOwner, msg.sender, _newPrice); emit LogBuy(msg.sender, _newPrice); } /* Only Patron Actions */ function depositWei() public payable collectPatronage onlyPatron { deposit = deposit.add(msg.value); } function changePrice(uint256 _newPrice) public collectPatronage onlyPatron { require(_newPrice > 0, 'Price is zero'); price = _newPrice; emit LogPriceChange(price); } function withdrawDeposit(uint256 _wei) public collectPatronage onlyPatron { _withdrawDeposit(_wei); } function exit() public collectPatronage onlyPatron { _withdrawDeposit(deposit); } /* Actions that don't affect state of the artwork */ /* Artist Actions */ function withdrawArtistFunds() public { require(msg.sender == artist, "Not artist"); uint256 toSend = artistFund; artistFund = 0; artist.transfer(toSend); } /* Withdrawing Stuck Deposits */ /* To reduce complexity, pull funds are entirely separate from current deposit */ function withdrawPullFunds() public { require(pullFunds[msg.sender] > 0, "No pull funds available."); uint256 toSend = pullFunds[msg.sender]; pullFunds[msg.sender] = 0; msg.sender.transfer(toSend); } /* internal */ function _withdrawDeposit(uint256 _wei) internal { // note: can withdraw whole deposit, which puts it in immediate to be foreclosed state. require(deposit >= _wei, 'Withdrawing too much'); deposit = deposit.sub(_wei); msg.sender.transfer(_wei); // msg.sender == patron _forecloseIfNecessary(); } function _forecloseIfNecessary() internal { if(deposit == 0) { // become steward of artwork (aka foreclose) address currentOwner = art.ownerOf(42); transferArtworkTo(currentOwner, address(this), 0); emit LogForeclosure(currentOwner); } } function transferArtworkTo(address _currentOwner, address _newOwner, uint256 _newPrice) internal { // note: it would also tabulate time held in stewardship by smart contract timeHeld[_currentOwner] = timeHeld[_currentOwner].add((timeLastCollected.sub(timeAcquired))); art.transferFrom(_currentOwner, _newOwner, 42); price = _newPrice; timeAcquired = now; patrons[_newOwner] = true; } } contract BlockReceiver { ArtSteward steward; constructor (address _steward) public { steward = ArtSteward(_steward); } function buy(uint256 currentPrice) public payable { uint256 price = 1 ether; // steward.buy{value: msg.value}(price, currentPrice); // note: for some reason, it can't determine difference between buy(uint256) & buy(uint256,uint256) // Thus: manually creating this call for testing address(steward).call.value(msg.value)(abi.encodeWithSignature("buy(uint256,uint256)", price, currentPrice)); } function withdrawPullFunds() public { steward.withdrawPullFunds(); } // no fallback // no receive // will cause ETH sends to revert } 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); } } library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } 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)); } } 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); } interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered 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`, `to` cannot be zero. * - `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`, `to` cannot be zero. * - `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`, `to` cannot be zero. * - `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; function setup() external; } interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } interface IERC721Metadata is IERC721 { /** * @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); } 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 Router { ArtSteward steward; bool public toBlock = true; constructor (address _steward) public { steward = ArtSteward(_steward); } function buy(uint256 currentPrice) public payable { // steward.buy{value: msg.value}(1 ether, currentPrice); // note: for some reason, it can't determine difference between buy(uint256) & buy(uint256,uint256) // Thus: manually creating this call for testing address(steward).call.value(msg.value)(abi.encodeWithSignature("buy(uint256,uint256)", 1 ether, currentPrice)); } function withdrawPullFunds() public { steward.withdrawPullFunds(); } fallback() external payable { if(toBlock) { revert('blocked'); } } function setBlock(bool _tb) public { toBlock = _tb; } } 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 Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } contract ERC165 is IERC165 { /** * @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; } } contract ERC721 is ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` // bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; // IMPLEMENTATION SPECIFIC VARS address public steward; bool public init; function setup() public override { require(init == false, "Artwork already initialized."); _name = "This Artwork Is Always On Sale 2"; _symbol = "TAIAOS2"; steward = msg.sender; // mint artwork _mint(steward, 42); // mint _setTokenURI(42, "https://thisartworkisalwaysonsale.com/metadata2"); // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC165); _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); init=true; } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev Gets the token name. * @return string representing the token name */ function name() public view override returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If a base URI is set (via {_setBaseURI}), it is added as a prefix to the * token's own URI (via {_setTokenURI}). * * If there is a base URI but no token URI, the token's ID will be used as * its URI when appending it to the base URI. This pattern for autogenerated * token URIs can lead to large gas savings. * * .Examples * |=== * |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()` * | "" * | "" * | "" * | "" * | "token.uri/123" * | "token.uri/123" * | "token.uri/" * | "123" * | "token.uri/123" * | "token.uri/" * | "" * | "token.uri/<tokenId>" * |=== * * Requirements: * * - `tokenId` must exist. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // If there is no base URI, return the token URI. if (bytes(_baseURI).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(_baseURI, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param operator operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not steward."); _transfer(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ /*function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); }*/ /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ /* function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); }*/ /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ /*function _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 the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); // address owner = ownerOf(tokenId); // return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); // MODIFIED: // Only the steward is allowed to transfer return (spender == steward); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ /*function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); }*/ /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ /*function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); }*/ /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: If all token IDs share a prefix (for example, if your URIs look like * `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } // removed docstring due to parsing errors /*function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, msg.sender, from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } }*/ function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` will be burned. * - `from` 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 { } }
0x6080604052600436106101815760003560e01c8063879d5aad116100d1578063a2b40d191161008a578063d6febde811610064578063d6febde814610634578063e29eb8361461066c578063e9fad8ee14610697578063f07af5f7146106ae57610181565b8063a2b40d19146105a3578063a97d70b1146105de578063d0e30db01461060957610181565b8063879d5aad146104605780638bb66d8a1461048b578063929417db146104bd5780639443c2e3146104e85780639fc7a65b14610513578063a035b1fe1461057857610181565b80633989e2311161013e57806355c3bf101161011857806355c3bf101461036a5780635d5a92fb146103955780635e67d521146103fa5780636c7f17fb1461041157610181565b80633989e231146102d157806343bc1612146102e85780634bd8aeac1461033f57610181565b80630ee591ba1461018657806315488b881461019d5780632ef46320146101a7578063301bd28e14610210578063325678031461026757806333289a4614610296575b600080fd5b34801561019257600080fd5b5061019b6106d9565b005b6101a5610817565b005b3480156101b357600080fd5b506101f6600480360360208110156101ca57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061098b565b604051808215151515815260200191505060405180910390f35b34801561021c57600080fd5b506102256109ab565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561027357600080fd5b5061027c6109d1565b604051808215151515815260200191505060405180910390f35b3480156102a257600080fd5b506102cf600480360360208110156102b957600080fd5b81019080803590602001909291905050506109fa565b005b3480156102dd57600080fd5b506102e6610b5d565b005b3480156102f457600080fd5b506102fd610c6c565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561034b57600080fd5b50610354610c92565b6040518082815260200191505060405180910390f35b34801561037657600080fd5b5061037f610c98565b6040518082815260200191505060405180910390f35b3480156103a157600080fd5b506103e4600480360360208110156103b857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610c9e565b6040518082815260200191505060405180910390f35b34801561040657600080fd5b5061040f610cb6565b005b34801561041d57600080fd5b5061044a6004803603602081101561043457600080fd5b8101908080359060200190929190505050610e3e565b6040518082815260200191505060405180910390f35b34801561046c57600080fd5b50610475610e72565b6040518082815260200191505060405180910390f35b34801561049757600080fd5b506104a0610f6b565b604051808381526020018281526020019250505060405180910390f35b3480156104c957600080fd5b506104d2610f7f565b6040518082815260200191505060405180910390f35b3480156104f457600080fd5b506104fd610fc5565b6040518082815260200191505060405180910390f35b34801561051f57600080fd5b506105626004803603602081101561053657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611001565b6040518082815260200191505060405180910390f35b34801561058457600080fd5b5061058d611019565b6040518082815260200191505060405180910390f35b3480156105af57600080fd5b506105dc600480360360208110156105c657600080fd5b810190808035906020019092919050505061101f565b005b3480156105ea57600080fd5b506105f3611225565b6040518082815260200191505060405180910390f35b34801561061557600080fd5b5061061e611261565b6040518082815260200191505060405180910390f35b61066a6004803603604081101561064a57600080fd5b810190808035906020019092919080359060200190929190505050611267565b005b34801561067857600080fd5b506106816115fd565b6040518082815260200191505060405180910390f35b3480156106a357600080fd5b506106ac611603565b005b3480156106ba57600080fd5b506106c3611767565b6040518082815260200191505060405180910390f35b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461079c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f4e6f74206172746973740000000000000000000000000000000000000000000081525060200191505060405180910390fd5b600060065490506000600681905550600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050158015610813573d6000803e3d6000fd5b5050565b61081f610b5d565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16636352211e602a6040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561089357600080fd5b505afa1580156108a7573d6000803e3d6000fd5b505050506040513d60208110156108bd57600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461096e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f4e6f7420706174726f6e0000000000000000000000000000000000000000000081525060200191505060405180910390fd5b610983346004546117b790919063ffffffff16565b600481905550565b60086020528060005260406000206000915054906101000a900460ff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000806109dc610f7f565b905060045481106109f15760019150506109f7565b60009150505b90565b610a02610b5d565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16636352211e602a6040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b158015610a7657600080fd5b505afa158015610a8a573d6000803e3d6000fd5b505050506040513d6020811015610aa057600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610b51576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f4e6f7420706174726f6e0000000000000000000000000000000000000000000081525060200191505060405180910390fd5b610b5a8161183f565b50565b6000805414610c6a576000610b70610f7f565b90506004548110610bda57610bca610bb982610bab600454610b9d6003544261176d90919063ffffffff16565b61192490919063ffffffff16565b6119aa90919063ffffffff16565b6003546117b790919063ffffffff16565b6003819055506004549050610be2565b426003819055505b610bf78160045461176d90919063ffffffff16565b600481905550610c12816002546117b790919063ffffffff16565b600281905550610c2d816006546117b790919063ffffffff16565b600681905550807f54acb82a9e70d7c289b149758d23167c915428ae854a7aa4abe5bf2f4ef29f3660405160405180910390a2610c686119f4565b505b565b600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60065481565b600a5481565b60076020528060005260406000206000915090505481565b6000600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205411610d6b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260188152602001807f4e6f2070756c6c2066756e647320617661696c61626c652e000000000000000081525060200191505060405180910390fd5b6000600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490506000600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055503373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050158015610e3a573d6000803e3d6000fd5b5050565b6000610e6b6301e13380610e5d8460005461192490919063ffffffff16565b6119aa90919063ffffffff16565b9050919050565b600080610eb66301e13380610ea8600c54610e9a600b5460005461192490919063ffffffff16565b6119aa90919063ffffffff16565b6119aa90919063ffffffff16565b90506000610ec2610fc5565b90506000811115610ef257610ee782610ed9610fc5565b6119aa90919063ffffffff16565b420192505050610f68565b6000821115610f60576000610f05610f7f565b9050610f56610f4582610f37600454610f296003544261176d90919063ffffffff16565b61192490919063ffffffff16565b6119aa90919063ffffffff16565b6003546117b790919063ffffffff16565b9350505050610f68565b600354925050505b90565b600080610f76610f7f565b42915091509091565b6000610fc06301e13380610fb2610fa16003544261176d90919063ffffffff16565b60005461192490919063ffffffff16565b6119aa90919063ffffffff16565b905090565b600080610fd0610f7f565b90506004548110610fe5576000915050610ffe565b610ffa8160045461176d90919063ffffffff16565b9150505b90565b60096020528060005260406000206000915090505481565b60005481565b611027610b5d565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16636352211e602a6040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561109b57600080fd5b505afa1580156110af573d6000803e3d6000fd5b505050506040513d60208110156110c557600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614611176576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f4e6f7420706174726f6e0000000000000000000000000000000000000000000081525060200191505060405180910390fd5b600081116111ec576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f5072696365206973207a65726f0000000000000000000000000000000000000081525060200191505060405180910390fd5b806000819055506000547f854d6511a28585103049c7770618450f7c9aeb580c69db2913d63869663f475160405160405180910390a250565b6000600a5460035411156112595761125261124d600a5460035461176d90919063ffffffff16565b610e3e565b905061125e565b600090505b90565b60045481565b61126f610b5d565b80600054146112e6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260178152602001807f43757272656e7420507269636520696e636f727265637400000000000000000081525060200191505060405180910390fd5b6000821161135c576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600d8152602001807f5072696365206973207a65726f0000000000000000000000000000000000000081525060200191505060405180910390fd5b60005434116113d3576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f4e6f7420656e6f7567680000000000000000000000000000000000000000000081525060200191505060405180910390fd5b6000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16636352211e602a6040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561144957600080fd5b505afa15801561145d573d6000803e3d6000fd5b505050506040513d602081101561147357600080fd5b81019080805190602001909291905050509050600061149f6004546000546117b790919063ffffffff16565b9050600081111561158657600082905060008173ffffffffffffffffffffffffffffffffffffffff166108fc849081150290604051600060405180830381858888f193505050509050806115835761153f83600760008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546117b790919063ffffffff16565b600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b50505b426003819055506115a26000543461176d90919063ffffffff16565b6004819055506115b3823386611b05565b833373ffffffffffffffffffffffffffffffffffffffff167f4f79409f494e81c38036d80aa8a6507c2cb08d90bfb2fead5519447646b3497e60405160405180910390a350505050565b60025481565b61160b610b5d565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16636352211e602a6040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b15801561167f57600080fd5b505afa158015611693573d6000803e3d6000fd5b505050506040513d60208110156116a957600080fd5b810190808051906020019092919050505073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161461175a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252600a8152602001807f4e6f7420706174726f6e0000000000000000000000000000000000000000000081525060200191505060405180910390fd5b61176560045461183f565b565b60035481565b60006117af83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611d11565b905092915050565b600080828401905083811015611835576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b8060045410156118b7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260148152602001807f5769746864726177696e6720746f6f206d75636800000000000000000000000081525060200191505060405180910390fd5b6118cc8160045461176d90919063ffffffff16565b6004819055503373ffffffffffffffffffffffffffffffffffffffff166108fc829081150290604051600060405180830381858888f19350505050158015611918573d6000803e3d6000fd5b506119216119f4565b50565b60008083141561193757600090506119a4565b600082840290508284828161194857fe5b041461199f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180611e986021913960400191505060405180910390fd5b809150505b92915050565b60006119ec83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250611dd1565b905092915050565b60006004541415611b03576000600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16636352211e602a6040518263ffffffff1660e01b81526004018082815260200191505060206040518083038186803b158015611a7557600080fd5b505afa158015611a89573d6000803e3d6000fd5b505050506040513d6020811015611a9f57600080fd5b81019080805190602001909291905050509050611abe81306000611b05565b8073ffffffffffffffffffffffffffffffffffffffff167f6d6bbefef62d4cb6d0e3a4dd306a71d3632319b1e03659513df86b247dd657fe60405160405180910390a2505b565b611b6d611b1f600a5460035461176d90919063ffffffff16565b600960008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546117b790919063ffffffff16565b600960008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd8484602a6040518463ffffffff1660e01b8152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050600060405180830381600087803b158015611c8e57600080fd5b505af1158015611ca2573d6000803e3d6000fd5b505050508060008190555042600a819055506001600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff021916908315150217905550505050565b6000838311158290611dbe576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611d83578082015181840152602081019050611d68565b50505050905090810190601f168015611db05780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b60008083118290611e7d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611e42578082015181840152602081019050611e27565b50505050905090810190601f168015611e6f5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b506000838581611e8957fe5b04905080915050939250505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a2646970667358221220358e109c807fad63a81f2671cea2baf77a38526a03bb9b5f97a228d5c4b005d464736f6c634300060a0033
[ 7, 11, 8, 9, 13, 5 ]
0x59876c7a2e76419f8b2b47dae1324b2de0fa6952
pragma solidity 0.6.8; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IMVDFunctionalitiesManager { function getProxy() external view returns (address); function setProxy() external; function init(address sourceLocation, uint256 getMinimumBlockNumberSourceLocationId, address getMinimumBlockNumberFunctionalityAddress, uint256 getEmergencyMinimumBlockNumberSourceLocationId, address getEmergencyMinimumBlockNumberFunctionalityAddress, uint256 getEmergencySurveyStakingSourceLocationId, address getEmergencySurveyStakingFunctionalityAddress, uint256 checkVoteResultSourceLocationId, address checkVoteResultFunctionalityAddress) external; function addFunctionality(string calldata codeName, address sourceLocation, uint256 sourceLocationId, address location, bool submitable, string calldata methodSignature, string calldata returnAbiParametersArray, bool isInternal, bool needsSender) external; function addFunctionality(string calldata codeName, address sourceLocation, uint256 sourceLocationId, address location, bool submitable, string calldata methodSignature, string calldata returnAbiParametersArray, bool isInternal, bool needsSender, uint256 position) external; function removeFunctionality(string calldata codeName) external returns(bool removed, uint256 position); function isValidFunctionality(address functionality) external view returns(bool); function isAuthorizedFunctionality(address functionality) external view returns(bool); function setCallingContext(address location) external returns(bool); function clearCallingContext() external; function getFunctionalityData(string calldata codeName) external view returns(address, uint256, string memory, address, uint256); function hasFunctionality(string calldata codeName) external view returns(bool); function getFunctionalitiesAmount() external view returns(uint256); function functionalitiesToJSON() external view returns(string memory); function functionalitiesToJSON(uint256 start, uint256 l) external view returns(string memory functionsJSONArray); function functionalityNames() external view returns(string memory); function functionalityNames(uint256 start, uint256 l) external view returns(string memory functionsJSONArray); function functionalityToJSON(string calldata codeName) external view returns(string memory); function preConditionCheck(string calldata codeName, bytes calldata data, uint8 submitable, address sender, uint256 value) external view returns(address location, bytes memory payload); function setupFunctionality(address proposalAddress) external returns (bool); } interface IMVDFunctionalityProposal { function init(string calldata codeName, address location, string calldata methodSignature, string calldata returnAbiParametersArray, string calldata replaces, address proxy) external; function setCollateralData(bool emergency, address sourceLocation, uint256 sourceLocationId, bool submitable, bool isInternal, bool needsSender, address proposer, uint256 votesHardCap) external; function getProxy() external view returns(address); function getCodeName() external view returns(string memory); function isEmergency() external view returns(bool); function getSourceLocation() external view returns(address); function getSourceLocationId() external view returns(uint256); function getLocation() external view returns(address); function isSubmitable() external view returns(bool); function getMethodSignature() external view returns(string memory); function getReturnAbiParametersArray() external view returns(string memory); function isInternal() external view returns(bool); function needsSender() external view returns(bool); function getReplaces() external view returns(string memory); function getProposer() external view returns(address); function getSurveyEndBlock() external view returns(uint256); function getSurveyDuration() external view returns(uint256); function isVotesHardCapReached() external view returns(bool); function getVotesHardCapToReach() external view returns(uint256); function toJSON() external view returns(string memory); function getVote(address addr) external view returns(uint256 accept, uint256 refuse); function getVotes() external view returns(uint256, uint256); function start() external; function disable() external; function isDisabled() external view returns(bool); function isTerminated() external view returns(bool); function accept(uint256 amount) external; function retireAccept(uint256 amount) external; function moveToAccept(uint256 amount) external; function refuse(uint256 amount) external; function retireRefuse(uint256 amount) external; function moveToRefuse(uint256 amount) external; function retireAll() external; function withdraw() external; function terminate() external; function set() external; event Accept(address indexed voter, uint256 amount); event RetireAccept(address indexed voter, uint256 amount); event MoveToAccept(address indexed voter, uint256 amount); event Refuse(address indexed voter, uint256 amount); event RetireRefuse(address indexed voter, uint256 amount); event MoveToRefuse(address indexed voter, uint256 amount); event RetireAll(address indexed voter, uint256 amount); } interface IMVDProxy { function init(address votingTokenAddress, address functionalityProposalManagerAddress, address stateHolderAddress, address functionalityModelsManagerAddress, address functionalitiesManagerAddress, address walletAddress) external; function getDelegates() external view returns(address,address,address,address,address,address); function getToken() external view returns(address); function getMVDFunctionalityProposalManagerAddress() external view returns(address); function getStateHolderAddress() external view returns(address); function getMVDFunctionalityModelsManagerAddress() external view returns(address); function getMVDFunctionalitiesManagerAddress() external view returns(address); function getMVDWalletAddress() external view returns(address); function setDelegate(uint256 position, address newAddress) external returns(address oldAddress); function changeProxy(address newAddress, bytes calldata initPayload) external; function isValidProposal(address proposal) external view returns (bool); function isAuthorizedFunctionality(address functionality) external view returns(bool); function newProposal(string calldata codeName, bool emergency, address sourceLocation, uint256 sourceLocationId, address location, bool submitable, string calldata methodSignature, string calldata returnParametersJSONArray, bool isInternal, bool needsSender, string calldata replaces) external returns(address proposalAddress); function startProposal(address proposalAddress) external; function disableProposal(address proposalAddress) external; function transfer(address receiver, uint256 value, address token) external; function transfer721(address receiver, uint256 tokenId, bytes calldata data, bool safe, address token) external; function setProposal() external; function read(string calldata codeName, bytes calldata data) external view returns(bytes memory returnData); function submit(string calldata codeName, bytes calldata data) external payable returns(bytes memory returnData); function callFromManager(address location, bytes calldata payload) external returns(bool, bytes memory); function emitFromManager(string calldata codeName, address proposal, string calldata replaced, address replacedSourceLocation, uint256 replacedSourceLocationId, address location, bool submitable, string calldata methodSignature, bool isInternal, bool needsSender, address proposalAddress) external; function emitEvent(string calldata eventSignature, bytes calldata firstIndex, bytes calldata secondIndex, bytes calldata data) external; event ProxyChanged(address indexed newAddress); event DelegateChanged(uint256 position, address indexed oldAddress, address indexed newAddress); event Proposal(address proposal); event ProposalCheck(address indexed proposal); event ProposalSet(address indexed proposal, bool success); event FunctionalitySet(string codeName, address indexed proposal, string replaced, address replacedSourceLocation, uint256 replacedSourceLocationId, address indexed replacedLocation, bool replacedWasSubmitable, string replacedMethodSignature, bool replacedWasInternal, bool replacedNeededSender, address indexed replacedProposal); event Event(string indexed key, bytes32 indexed firstIndex, bytes32 indexed secondIndex, bytes data); } contract MVDFunctionalityProposal is IMVDFunctionalityProposal{ bool private _collateralDataSet; address private _proxy; address private _token; string private _codeName; bool private _emergency; address private _sourceLocation; uint256 private _sourceLocationId; address private _location; bool private _submitable; string private _methodSignature; string private _returnAbiParametersArray; bool private _isInternal; bool private _needsSender; string private _replaces; uint256 private _surveyEndBlock; uint256 private _surveyDuration; bool private _terminated; address private _proposer; bool private _disabled; mapping(address => uint256) private _accept; mapping(address => uint256) private _refuse; uint256 private _totalAccept; uint256 private _totalRefuse; mapping(address => bool) private _withdrawed; uint256 private _votesHardCap; bool private _votesHardCapReached; constructor(string memory codeName, address location, string memory methodSignature, string memory returnAbiParametersArray, string memory replaces, address proxy) public { init(codeName, location, methodSignature, returnAbiParametersArray, replaces, proxy); } function init(string memory codeName, address location, string memory methodSignature, string memory returnAbiParametersArray, string memory replaces, address proxy) public override { require(_proxy == address(0), "Already initialized!"); _token = IMVDProxy(_proxy = proxy).getToken(); _codeName = codeName; _location = location; _methodSignature = methodSignature; _returnAbiParametersArray = returnAbiParametersArray; _replaces = replaces; } function setCollateralData(bool emergency, address sourceLocation, uint256 sourceLocationId, bool submitable, bool isInternal, bool needsSender, address proposer, uint256 votesHardCap) public override { require(!_collateralDataSet, "setCollateralData already called!"); require(_proxy == msg.sender, "Only Original Proxy can call this method!"); _sourceLocation = sourceLocation; _sourceLocationId = sourceLocationId; _submitable = submitable; _isInternal = isInternal; _needsSender = needsSender; _proposer = proposer; _surveyDuration = toUint256(IMVDProxy(_proxy).read((_emergency = emergency) ? "getMinimumBlockNumberForEmergencySurvey" : "getMinimumBlockNumberForSurvey", bytes(""))); _votesHardCap = votesHardCap; _collateralDataSet = true; } function getProxy() public override view returns(address) { return _proxy; } function getCodeName() public override view returns(string memory) { return _codeName; } function isEmergency() public override view returns(bool) { return _emergency; } function getSourceLocation() public override view returns(address) { return _sourceLocation; } function getSourceLocationId() public override view returns(uint256) { return _sourceLocationId; } function getLocation() public override view returns(address) { return _location; } function isSubmitable() public override view returns(bool) { return _submitable; } function getMethodSignature() public override view returns(string memory) { return _methodSignature; } function getReturnAbiParametersArray() public override view returns(string memory) { return _returnAbiParametersArray; } function isInternal() public override view returns(bool) { return _isInternal; } function needsSender() public override view returns(bool) { return _needsSender; } function getReplaces() public override view returns(string memory) { return _replaces; } function getProposer() public override view returns(address) { return _proposer; } function getSurveyEndBlock() public override view returns(uint256) { return _surveyEndBlock; } function getSurveyDuration() public override view returns(uint256) { return _surveyDuration; } function getVote(address addr) public override view returns(uint256 accept, uint256 refuse) { accept = _accept[addr]; refuse = _refuse[addr]; } function getVotes() public override view returns(uint256, uint256) { return (_totalAccept, _totalRefuse); } function isTerminated() public override view returns(bool) { return _terminated; } function isDisabled() public override view returns(bool) { return _disabled; } function isVotesHardCapReached() public override view returns(bool) { return _votesHardCapReached; } function getVotesHardCapToReach() public override view returns(uint256) { return _votesHardCap; } function start() public override { require(_collateralDataSet, "Still waiting for setCollateralData to be called!"); require(msg.sender == _proxy, "Only Proxy can call this function!"); require(_surveyEndBlock == 0, "Already started!"); require(!_disabled, "Already disabled!"); _surveyEndBlock = block.number + _surveyDuration; } function disable() public override { require(_collateralDataSet, "Still waiting for setCollateralData to be called!"); require(msg.sender == _proxy, "Only Proxy can call this function!"); require(_surveyEndBlock == 0, "Already started!"); _disabled = true; _terminated = true; } function toJSON() public override view returns(string memory) { return string(abi.encodePacked( '{', getFirstJSONPart(_sourceLocation, _sourceLocationId, _location), '","submitable":', _submitable ? "true" : "false", ',"emergency":', _emergency ? "true" : "false", ',"isInternal":', _isInternal ? "true" : "false", ',"needsSender":', _needsSender ? "true" : "false", ',', getSecondJSONPart(), ',"proposer":"', toString(_proposer), '","endBlock":', toString(_surveyEndBlock), ',"terminated":', _terminated ? "true" : "false", ',"accepted":', toString(_totalAccept), ',"refused":', toString(_totalRefuse), ',"disabled":', _disabled ? 'true' : 'false', '}') ); } function getSecondJSONPart() private view returns (string memory){ return string(abi.encodePacked( '"codeName":"', _codeName, '","methodSignature":"', _methodSignature, '","returnAbiParametersArray":', formatReturnAbiParametersArray(_returnAbiParametersArray), ',"replaces":"', _replaces, '"')); } modifier duringSurvey() { require(_collateralDataSet, "Still waiting for setCollateralData to be called!"); require(!_disabled, "Survey disabled!"); require(!_terminated, "Survey Terminated!"); require(!_votesHardCapReached, "Votes Hard Cap reached!"); require(_surveyEndBlock > 0, "Survey Not Started!"); require(block.number < _surveyEndBlock, "Survey ended!"); _; } modifier onSurveyEnd() { require(_collateralDataSet, "Still waiting for setCollateralData to be called!"); require(!_disabled, "Survey disabled!"); require(_surveyEndBlock > 0, "Survey Not Started!"); if(!_votesHardCapReached) { require(block.number >= _surveyEndBlock, "Survey is still running!"); } _; } function _checkVotesHardCap() private { if(_votesHardCap == 0 || (_totalAccept < _votesHardCap && _totalRefuse < _votesHardCap)) { return; } _votesHardCapReached = true; terminate(); } function accept(uint256 amount) external override duringSurvey { IERC20(_token).transferFrom(msg.sender, address(this), amount); uint256 vote = _accept[msg.sender]; vote += amount; _accept[msg.sender] = vote; _totalAccept += amount; emit Accept(msg.sender, amount); _checkVotesHardCap(); } function retireAccept(uint256 amount) external override duringSurvey { require(_accept[msg.sender] >= amount, "Insufficient funds!"); IERC20(_token).transfer(msg.sender, amount); uint256 vote = _accept[msg.sender]; vote -= amount; _accept[msg.sender] = vote; _totalAccept -= amount; emit RetireAccept(msg.sender, amount); } function moveToAccept(uint256 amount) external override duringSurvey { require(_refuse[msg.sender] >= amount, "Insufficient funds!"); uint256 vote = _refuse[msg.sender]; vote -= amount; _refuse[msg.sender] = vote; _totalRefuse -= amount; vote = _accept[msg.sender]; vote += amount; _accept[msg.sender] = vote; _totalAccept += amount; emit MoveToAccept(msg.sender, amount); _checkVotesHardCap(); } function refuse(uint256 amount) external override duringSurvey { IERC20(_token).transferFrom(msg.sender, address(this), amount); uint256 vote = _refuse[msg.sender]; vote += amount; _refuse[msg.sender] = vote; _totalRefuse += amount; emit Refuse(msg.sender, amount); _checkVotesHardCap(); } function retireRefuse(uint256 amount) external override duringSurvey { require(_refuse[msg.sender] >= amount, "Insufficient funds!"); IERC20(_token).transfer(msg.sender, amount); uint256 vote = _refuse[msg.sender]; vote -= amount; _refuse[msg.sender] = vote; _totalRefuse -= amount; emit RetireRefuse(msg.sender, amount); } function moveToRefuse(uint256 amount) external override duringSurvey { require(_accept[msg.sender] >= amount, "Insufficient funds!"); uint256 vote = _accept[msg.sender]; vote -= amount; _accept[msg.sender] = vote; _totalAccept -= amount; vote = _refuse[msg.sender]; vote += amount; _refuse[msg.sender] = vote; _totalRefuse += amount; emit MoveToRefuse(msg.sender, amount); _checkVotesHardCap(); } function retireAll() external override duringSurvey { require(_accept[msg.sender] + _refuse[msg.sender] > 0, "No votes!"); uint256 acpt = _accept[msg.sender]; uint256 rfs = _refuse[msg.sender]; IERC20(_token).transfer(msg.sender, acpt + rfs); _accept[msg.sender] = 0; _refuse[msg.sender] = 0; _totalAccept -= acpt; _totalRefuse -= rfs; emit RetireAll(msg.sender, acpt + rfs); } function withdraw() external override onSurveyEnd { if(!_terminated && !_disabled) { terminate(); return; } _withdraw(true); } function terminate() public override onSurveyEnd { require(!_terminated, "Already terminated!"); IMVDProxy(_proxy).setProposal(); _withdraw(false); } function _withdraw(bool launchError) private { require(!launchError || _accept[msg.sender] + _refuse[msg.sender] > 0, "Nothing to Withdraw!"); require(!launchError || !_withdrawed[msg.sender], "Already Withdrawed!"); if(_accept[msg.sender] + _refuse[msg.sender] > 0 && !_withdrawed[msg.sender]) { IERC20(_token).transfer(msg.sender, _accept[msg.sender] + _refuse[msg.sender]); _withdrawed[msg.sender] = true; } } function set() public override onSurveyEnd { require(msg.sender == _proxy, "Unauthorized Access!"); require(!_terminated, "Already terminated!"); _terminated = true; } function toUint256(bytes memory bs) public pure returns(uint256 x) { if(bs.length >= 32) { assembly { x := mload(add(bs, add(0x20, 0))) } } } function toString(address _addr) public pure returns(string memory) { bytes32 value = bytes32(uint256(_addr)); bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(42); str[0] = '0'; str[1] = 'x'; for (uint i = 0; i < 20; i++) { str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))]; str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))]; } return string(str); } function toString(uint _i) public pure returns(string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function getFirstJSONPart(address sourceLocation, uint256 sourceLocationId, address location) public pure returns(bytes memory) { return abi.encodePacked( '"sourceLocation":"', toString(sourceLocation), '","sourceLocationId":', toString(sourceLocationId), ',"location":"', toString(location) ); } function formatReturnAbiParametersArray(string memory m) public pure returns(string memory) { bytes memory b = bytes(m); if(b.length < 2) { return "[]"; } if(b[0] != bytes1("[")) { return "[]"; } if(b[b.length - 1] != bytes1("]")) { return "[]"; } return m; } }
0x608060405234801561001057600080fd5b50600436106102535760003560e01c806366844c7e11610146578063b8e010de116100c3578063d1cc997611610087578063d1cc9976146108e9578063e9790d02146108f1578063eb3464a1146108f9578063eba3aa4214610916578063ef0e99a71461091e578063f48f489e1461093b57610253565b8063b8e010de14610825578063b9c33b261461082d578063bd37c8aa14610835578063be9a6555146108d9578063ce2ce3fc146108e157610253565b80638fc38e0b1161010a5780638fc38e0b146107cc578063933a9ce8146107d4578063a60a07b2146107f8578063aa1cc2e914610815578063b23d26521461081d57610253565b806366844c7e146107075780636900a3ae146107245780636c57f5a9146107415780638d06bc5b146107495780638d337b81146107a657610253565b80633ccfd60b116101d457806355d92ae31161019857806355d92ae31461061057806356ca623e146106185780635ad3c9311461063e5780635f9e8f82146106e257806366698389146106ea57610253565b80633ccfd60b146105d65780633e1b421d146105de5780633fa4d9ca146105e65780634398037c14610600578063485e2d9e1461060857610253565b806316375cb31161021b57806316375cb31461056b57806316e29d711461057357806319b05f491461057b5780632c394d99146105985780632f2770db146105ce57610253565b806304f181b7146102585780630c08bf88146102d55780630dc96015146102df57806314ebd7831461030057806315db404e1461054f575b600080fd5b610260610943565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561029a578181015183820152602001610282565b50505050905090810190601f1680156102c75780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102dd6109da565b005b6102e7610bd0565b6040805192835260208301919091528051918290030190f35b6102dd600480360360c081101561031657600080fd5b810190602081018135600160201b81111561033057600080fd5b82018360208201111561034257600080fd5b803590602001918460018302840111600160201b8311171561036357600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092956001600160a01b03853516959094909350604081019250602001359050600160201b8111156103c657600080fd5b8201836020820111156103d857600080fd5b803590602001918460018302840111600160201b831117156103f957600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b81111561044b57600080fd5b82018360208201111561045d57600080fd5b803590602001918460018302840111600160201b8311171561047e57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295949360208101935035915050600160201b8111156104d057600080fd5b8201836020820111156104e257600080fd5b803590602001918460018302840111600160201b8311171561050357600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550505090356001600160a01b03169150610bda9050565b610557610d50565b604080519115158252519081900360200190f35b610260610d59565b61055761144c565b6102dd6004803603602081101561059157600080fd5b5035611455565b610260600480360360608110156105ae57600080fd5b506001600160a01b038135811691602081013591604090910135166116ee565b6102dd611863565b6102dd611958565b610260611ac5565b6105ee611b26565b60408051918252519081900360200190f35b610260611b2c565b6105ee611b8a565b610557611b90565b6102606004803603602081101561062e57600080fd5b50356001600160a01b0316611ba0565b6102606004803603602081101561065457600080fd5b810190602081018135600160201b81111561066e57600080fd5b82018360208201111561068057600080fd5b803590602001918460018302840111600160201b831117156106a157600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550611d1e945050505050565b610557611df1565b6102dd6004803603602081101561070057600080fd5b5035611dfa565b6102dd6004803603602081101561071d57600080fd5b503561207a565b6102606004803603602081101561073a57600080fd5b50356122fa565b6105576123c9565b6102dd600480360361010081101561076057600080fd5b5080351515906001600160a01b0360208201358116916040810135916060820135151591608081013515159160a082013515159160c08101359091169060e001356123d9565b6102e7600480360360208110156107bc57600080fd5b50356001600160a01b0316612763565b6105ee61278b565b6107dc612791565b604080516001600160a01b039092168252519081900360200190f35b6102dd6004803603602081101561080e57600080fd5b50356127a5565b6105ee612a3a565b610557612a40565b6102dd612a4e565b6107dc612c3a565b6105ee6004803603602081101561084b57600080fd5b810190602081018135600160201b81111561086557600080fd5b82018360208201111561087757600080fd5b803590602001918460018302840111600160201b8311171561089857600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550612c4e945050505050565b6102dd612c61565b6107dc612d95565b610557612da4565b6107dc612dad565b6102dd6004803603602081101561090f57600080fd5b5035612dc1565b6102dd6130a8565b6102dd6004803603602081101561093457600080fd5b50356133b8565b61026061369f565b60078054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156109cf5780601f106109a4576101008083540402835291602001916109cf565b820191906000526020600020905b8154815290600101906020018083116109b257829003601f168201915b505050505090505b90565b60005460ff16610a1b5760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff1615610a6d576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b6000600a5411610ab2576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b60135460ff16610b0e57600a54431015610b0e576040805162461bcd60e51b8152602060048201526018602482015277537572766579206973207374696c6c2072756e6e696e672160401b604482015290519081900360640190fd5b600c5460ff1615610b5c576040805162461bcd60e51b8152602060048201526013602482015272416c7265616479207465726d696e617465642160681b604482015290519081900360640190fd5b600060019054906101000a90046001600160a01b03166001600160a01b0316632a7434a86040518163ffffffff1660e01b8152600401600060405180830381600087803b158015610bac57600080fd5b505af1158015610bc0573d6000803e3d6000fd5b50505050610bce6000613700565b565b600f546010549091565b60005461010090046001600160a01b031615610c34576040805162461bcd60e51b8152602060048201526014602482015273416c726561647920696e697469616c697a65642160601b604482015290519081900360640190fd5b80600060016101000a8154816001600160a01b0302191690836001600160a01b0316021790556001600160a01b03166321df0da76040518163ffffffff1660e01b815260040160206040518083038186803b158015610c9257600080fd5b505afa158015610ca6573d6000803e3d6000fd5b505050506040513d6020811015610cbc57600080fd5b5051600180546001600160a01b0319166001600160a01b039092169190911790558551610cf0906002906020890190613b9a565b50600580546001600160a01b0319166001600160a01b0387161790558351610d1f906006906020870190613b9a565b508251610d33906007906020860190613b9a565b508151610d47906009906020850190613b9a565b50505050505050565b60135460ff1690565b600354600454600554606092610d81926101009091046001600160a01b0390811692166116ee565b600554600160a01b900460ff16610db5576040518060400160405280600581526020016466616c736560d81b815250610dd3565b604051806040016040528060048152602001637472756560e01b8152505b60035460ff16610e00576040518060400160405280600581526020016466616c736560d81b815250610e1e565b604051806040016040528060048152602001637472756560e01b8152505b60085460ff16610e4b576040518060400160405280600581526020016466616c736560d81b815250610e69565b604051806040016040528060048152602001637472756560e01b8152505b600854610100900460ff16610e9b576040518060400160405280600581526020016466616c736560d81b815250610eb9565b604051806040016040528060048152602001637472756560e01b8152505b610ec16138c6565b600c54610edb9061010090046001600160a01b0316611ba0565b610ee6600a546122fa565b600c5460ff16610f13576040518060400160405280600581526020016466616c736560d81b815250610f31565b604051806040016040528060048152602001637472756560e01b8152505b610f3c600f546122fa565b610f476010546122fa565b600c54600160a81b900460ff16610f7b576040518060400160405280600581526020016466616c736560d81b815250610f99565b604051806040016040528060048152602001637472756560e01b8152505b6040516020018080607b60f81b8152506001018d805190602001908083835b60208310610fd75780518252601f199092019160209182019101610fb8565b51815160209384036101000a60001901801990921691161790526e11161139bab136b4ba30b13632911d60891b919093019081528e51600f909101928f0191508083835b6020831061103a5780518252601f19909201916020918201910161101b565b51815160209384036101000a60001901801990921691161790526c161132b6b2b933b2b731bc911d60991b919093019081528d51600d909101928e0191508083835b6020831061109b5780518252601f19909201916020918201910161107c565b51815160209384036101000a60001901801990921691161790526d161134b9a4b73a32b93730b6111d60911b919093019081528c51600e909101928d0191508083835b602083106110fd5780518252601f1990920191602091820191016110de565b51815160209384036101000a60001901801990921691161790526e16113732b2b239a9b2b73232b9111d60891b919093019081528b51600f909101928c0191508083835b602083106111605780518252601f199092019160209182019101611141565b6001836020036101000a03801982511681845116808217855250505050505090500180600b60fa1b81525060010188805190602001908083835b602083106111b95780518252601f19909201916020918201910161119a565b51815160209384036101000a60001901801990921691161790526c1611383937b837b9b2b9111d1160991b919093019081528951600d909101928a0191508083835b6020831061121a5780518252601f1990920191602091820191016111fb565b51815160209384036101000a60001901801990921691161790526c11161132b732213637b1b5911d60991b919093019081528851600d90910192890191508083835b6020831061127b5780518252601f19909201916020918201910161125c565b51815160209384036101000a60001901801990921691161790526d16113a32b936b4b730ba32b2111d60911b919093019081528751600e90910192880191508083835b602083106112dd5780518252601f1990920191602091820191016112be565b51815160209384036101000a60001901801990921691161790526b161130b1b1b2b83a32b2111d60a11b919093019081528651600c90910192870191508083835b6020831061133d5780518252601f19909201916020918201910161131e565b51815160209384036101000a60001901801990921691161790526a16113932b33ab9b2b2111d60a91b919093019081528551600b90910192860191508083835b6020831061139c5780518252601f19909201916020918201910161137d565b51815160209384036101000a60001901801990921691161790526b16113234b9b0b13632b2111d60a11b919093019081528451600c90910192850191508083835b602083106113fc5780518252601f1990920191602091820191016113dd565b6001836020036101000a03801982511681845116808217855250505050505090500180607d60f81b8152506001019c50505050505050505050505050604051602081830303815290604052905090565b60085460ff1690565b60005460ff166114965760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff16156114e8576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b600c5460ff1615611535576040805162461bcd60e51b8152602060048201526012602482015271537572766579205465726d696e617465642160701b604482015290519081900360640190fd5b60135460ff161561157b576040805162461bcd60e51b81526020600482015260176024820152600080516020613c33833981519152604482015290519081900360640190fd5b6000600a54116115c0576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b600a544310611606576040805162461bcd60e51b815260206004820152600d60248201526c53757276657920656e6465642160981b604482015290519081900360640190fd5b600154604080516323b872dd60e01b81523360048201523060248201526044810184905290516001600160a01b03909216916323b872dd916064808201926020929091908290030181600087803b15801561166057600080fd5b505af1158015611674573d6000803e3d6000fd5b505050506040513d602081101561168a57600080fd5b5050336000818152600d60209081526040918290208054850190819055600f805486019055825185815292519093927f68e07974e86f9190b39c5e1783e6ba66b3d0d7ccf507de51450f14e594d1686892908290030190a26116ea613b5b565b5050565b60606116f984611ba0565b611702846122fa565b61170b84611ba0565b6040516020018080711139b7bab931b2a637b1b0ba34b7b7111d1160711b81525060120184805190602001908083835b6020831061175a5780518252601f19909201916020918201910161173b565b51815160209384036101000a60001901801990921691161790527411161139b7bab931b2a637b1b0ba34b7b724b2111d60591b919093019081528551601590910192860191508083835b602083106117c35780518252601f1990920191602091820191016117a4565b51815160209384036101000a60001901801990921691161790526c16113637b1b0ba34b7b7111d1160991b919093019081528451600d90910192850191508083835b602083106118245780518252601f199092019160209182019101611805565b6001836020036101000a038019825116818451168082178552505050505050905001935050505060405160208183030381529060405290509392505050565b60005460ff166118a45760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b60005461010090046001600160a01b031633146118f25760405162461bcd60e51b8152600401808060200182810382526022815260200180613c7a6022913960400191505060405180910390fd5b600a541561193a576040805162461bcd60e51b815260206004820152601060248201526f416c726561647920737461727465642160801b604482015290519081900360640190fd5b600c805460ff1960ff60a81b19909116600160a81b17166001179055565b60005460ff166119995760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff16156119eb576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b6000600a5411611a30576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b60135460ff16611a8c57600a54431015611a8c576040805162461bcd60e51b8152602060048201526018602482015277537572766579206973207374696c6c2072756e6e696e672160401b604482015290519081900360640190fd5b600c5460ff16158015611aa95750600c54600160a81b900460ff16155b15611abb57611ab66109da565b610bce565b610bce6001613700565b60068054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156109cf5780601f106109a4576101008083540402835291602001916109cf565b600a5490565b60028054604080516020601f60001961010060018716150201909416859004938401819004810282018101909252828152606093909290918301828280156109cf5780601f106109a4576101008083540402835291602001916109cf565b60045490565b600554600160a01b900460ff1690565b604080518082018252601081526f181899199a1a9b1b9c1cb0b131b232b360811b60208201528151602a80825260608281019094526001600160a01b03851692918491602082018180368337019050509050600360fc1b81600081518110611c0457fe5b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110611c2d57fe5b60200101906001600160f81b031916908160001a90535060005b6014811015611d13578260048583600c0160208110611c6257fe5b1a60f81b6001600160f81b031916901c60f81c60ff1681518110611c8257fe5b602001015160f81c60f81b828260020260020181518110611c9f57fe5b60200101906001600160f81b031916908160001a905350828482600c0160208110611cc657fe5b825191901a600f16908110611cd757fe5b602001015160f81c60f81b828260020260030181518110611cf457fe5b60200101906001600160f81b031916908160001a905350600101611c47565b50925050505b919050565b606080829050600281511015611d4e5750506040805180820190915260028152615b5d60f01b6020820152611d19565b605b60f81b6001600160f81b03191681600081518110611d6a57fe5b01602001516001600160f81b03191614611d9e5750506040805180820190915260028152615b5d60f01b6020820152611d19565b8051605d60f81b9082906000198101908110611db657fe5b01602001516001600160f81b03191614611dea5750506040805180820190915260028152615b5d60f01b6020820152611d19565b5090919050565b60035460ff1690565b60005460ff16611e3b5760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff1615611e8d576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b600c5460ff1615611eda576040805162461bcd60e51b8152602060048201526012602482015271537572766579205465726d696e617465642160701b604482015290519081900360640190fd5b60135460ff1615611f20576040805162461bcd60e51b81526020600482015260176024820152600080516020613c33833981519152604482015290519081900360640190fd5b6000600a5411611f65576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b600a544310611fab576040805162461bcd60e51b815260206004820152600d60248201526c53757276657920656e6465642160981b604482015290519081900360640190fd5b336000908152600d6020526040902054811115612005576040805162461bcd60e51b8152602060048201526013602482015272496e73756666696369656e742066756e64732160681b604482015290519081900360640190fd5b336000818152600d6020908152604080832080548690039055600f80548690039055600e82529182902080548501908190556010805486019055825185815292519093927f66ac89bb1a67976b7989a763cdec43b50a592dc86bb59f48d08e26572cb1522192908290030190a26116ea613b5b565b60005460ff166120bb5760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff161561210d576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b600c5460ff161561215a576040805162461bcd60e51b8152602060048201526012602482015271537572766579205465726d696e617465642160701b604482015290519081900360640190fd5b60135460ff16156121a0576040805162461bcd60e51b81526020600482015260176024820152600080516020613c33833981519152604482015290519081900360640190fd5b6000600a54116121e5576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b600a54431061222b576040805162461bcd60e51b815260206004820152600d60248201526c53757276657920656e6465642160981b604482015290519081900360640190fd5b336000908152600e6020526040902054811115612285576040805162461bcd60e51b8152602060048201526013602482015272496e73756666696369656e742066756e64732160681b604482015290519081900360640190fd5b336000818152600e6020908152604080832080548690039055601080548690039055600d8252918290208054850190819055600f805486019055825185815292519093927f483d089c46398a02a8985779ec41436d62364736e8a9b40a10183fa12867839292908290030190a26116ea613b5b565b60608161231f57506040805180820190915260018152600360fc1b6020820152611d19565b8160005b811561233757600101600a82049150612323565b60608167ffffffffffffffff8111801561235057600080fd5b506040519080825280601f01601f19166020018201604052801561237b576020820181803683370190505b50905060001982015b8515611d1357600a860660300160f81b828280600190039350815181106123a757fe5b60200101906001600160f81b031916908160001a905350600a86049550612384565b600c54600160a81b900460ff1690565b60005460ff161561241b5760405162461bcd60e51b8152600401808060200182810382526021815260200180613d166021913960400191505060405180910390fd5b60005461010090046001600160a01b031633146124695760405162461bcd60e51b8152600401808060200182810382526029815260200180613c9c6029913960400191505060405180910390fd5b6003805460048890556005805460ff60a01b1916600160a01b891515021790556008805460ff199081168815151761ff001916610100881515810291909117909255600c8054610100600160a81b03199081166001600160a01b0389811686029190911790925560005494168c82168402179091168c1515179093556127479291041663841d0ed78a612531576040518060400160405280601e81526020017f6765744d696e696d756d426c6f636b4e756d626572466f72537572766579000081525061254b565b604051806060016040528060278152602001613c53602791395b604051806020016040528060008152506040518363ffffffff1660e01b8152600401808060200180602001838103835285818151815260200191508051906020019080838360005b838110156125ab578181015183820152602001612593565b50505050905090810190601f1680156125d85780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b8381101561260b5781810151838201526020016125f3565b50505050905090810190601f1680156126385780820380516001836020036101000a031916815260200191505b5094505050505060006040518083038186803b15801561265757600080fd5b505afa15801561266b573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561269457600080fd5b8101908080516040519392919084600160201b8211156126b357600080fd5b9083019060208201858111156126c857600080fd5b8251600160201b8111828201881017156126e157600080fd5b82525081516020918201929091019080838360005b8381101561270e5781810151838201526020016126f6565b50505050905090810190601f16801561273b5780820380516001836020036101000a031916815260200191505b50604052505050612c4e565b600b5560125550506000805460ff191660011790555050505050565b6001600160a01b03166000908152600d6020908152604080832054600e909252909120549091565b600b5490565b60005461010090046001600160a01b031690565b60005460ff166127e65760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff1615612838576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b600c5460ff1615612885576040805162461bcd60e51b8152602060048201526012602482015271537572766579205465726d696e617465642160701b604482015290519081900360640190fd5b60135460ff16156128cb576040805162461bcd60e51b81526020600482015260176024820152600080516020613c33833981519152604482015290519081900360640190fd5b6000600a5411612910576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b600a544310612956576040805162461bcd60e51b815260206004820152600d60248201526c53757276657920656e6465642160981b604482015290519081900360640190fd5b600154604080516323b872dd60e01b81523360048201523060248201526044810184905290516001600160a01b03909216916323b872dd916064808201926020929091908290030181600087803b1580156129b057600080fd5b505af11580156129c4573d6000803e3d6000fd5b505050506040513d60208110156129da57600080fd5b5050336000818152600e602090815260409182902080548501908190556010805486019055825185815292519093927f4e855894dd91aeb0192726b247db8c42f6d1275c4094286dfeadd2005971a1b492908290030190a26116ea613b5b565b60125490565b600854610100900460ff1690565b60005460ff16612a8f5760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff1615612ae1576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b6000600a5411612b26576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b60135460ff16612b8257600a54431015612b82576040805162461bcd60e51b8152602060048201526018602482015277537572766579206973207374696c6c2072756e6e696e672160401b604482015290519081900360640190fd5b60005461010090046001600160a01b03163314612bdd576040805162461bcd60e51b8152602060048201526014602482015273556e617574686f72697a6564204163636573732160601b604482015290519081900360640190fd5b600c5460ff1615612c2b576040805162461bcd60e51b8152602060048201526013602482015272416c7265616479207465726d696e617465642160681b604482015290519081900360640190fd5b600c805460ff19166001179055565b60035461010090046001600160a01b031690565b60006020825110611d1957506020015190565b60005460ff16612ca25760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b60005461010090046001600160a01b03163314612cf05760405162461bcd60e51b8152600401808060200182810382526022815260200180613c7a6022913960400191505060405180910390fd5b600a5415612d38576040805162461bcd60e51b815260206004820152601060248201526f416c726561647920737461727465642160801b604482015290519081900360640190fd5b600c54600160a81b900460ff1615612d8b576040805162461bcd60e51b8152602060048201526011602482015270416c72656164792064697361626c65642160781b604482015290519081900360640190fd5b600b544301600a55565b6005546001600160a01b031690565b600c5460ff1690565b600c5461010090046001600160a01b031690565b60005460ff16612e025760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff1615612e54576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b600c5460ff1615612ea1576040805162461bcd60e51b8152602060048201526012602482015271537572766579205465726d696e617465642160701b604482015290519081900360640190fd5b60135460ff1615612ee7576040805162461bcd60e51b81526020600482015260176024820152600080516020613c33833981519152604482015290519081900360640190fd5b6000600a5411612f2c576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b600a544310612f72576040805162461bcd60e51b815260206004820152600d60248201526c53757276657920656e6465642160981b604482015290519081900360640190fd5b336000908152600e6020526040902054811115612fcc576040805162461bcd60e51b8152602060048201526013602482015272496e73756666696369656e742066756e64732160681b604482015290519081900360640190fd5b6001546040805163a9059cbb60e01b81523360048201526024810184905290516001600160a01b039092169163a9059cbb916044808201926020929091908290030181600087803b15801561302057600080fd5b505af1158015613034573d6000803e3d6000fd5b505050506040513d602081101561304a57600080fd5b5050336000818152600e6020908152604091829020805485900390819055601080548690039055825185815292519093927fa369065c2bc9cea922be2bf705101c039bc3af5575b8548b4d16d6a0b1893e2592908290030190a25050565b60005460ff166130e95760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff161561313b576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b600c5460ff1615613188576040805162461bcd60e51b8152602060048201526012602482015271537572766579205465726d696e617465642160701b604482015290519081900360640190fd5b60135460ff16156131ce576040805162461bcd60e51b81526020600482015260176024820152600080516020613c33833981519152604482015290519081900360640190fd5b6000600a5411613213576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b600a544310613259576040805162461bcd60e51b815260206004820152600d60248201526c53757276657920656e6465642160981b604482015290519081900360640190fd5b336000908152600e6020908152604080832054600d90925290912054016132b3576040805162461bcd60e51b81526020600482015260096024820152684e6f20766f7465732160b81b604482015290519081900360640190fd5b336000818152600d6020908152604080832054600e835281842054600154835163a9059cbb60e01b8152600481019790975281830160248801529251919590946001600160a01b039093169363a9059cbb9360448084019492938390030190829087803b15801561332357600080fd5b505af1158015613337573d6000803e3d6000fd5b505050506040513d602081101561334d57600080fd5b5050336000818152600d60209081526040808320839055600e825280832092909255600f805486900390556010805485900390558151848601815291517f1dd395e89b5da0e80f0242ec498fdfcaa6bc77d32b4417d89ec195e160fd7ad89281900390910190a25050565b60005460ff166133f95760405162461bcd60e51b8152600401808060200182810382526031815260200180613cc56031913960400191505060405180910390fd5b600c54600160a81b900460ff161561344b576040805162461bcd60e51b815260206004820152601060248201526f5375727665792064697361626c65642160801b604482015290519081900360640190fd5b600c5460ff1615613498576040805162461bcd60e51b8152602060048201526012602482015271537572766579205465726d696e617465642160701b604482015290519081900360640190fd5b60135460ff16156134de576040805162461bcd60e51b81526020600482015260176024820152600080516020613c33833981519152604482015290519081900360640190fd5b6000600a5411613523576040805162461bcd60e51b81526020600482015260136024820152600080516020613cf6833981519152604482015290519081900360640190fd5b600a544310613569576040805162461bcd60e51b815260206004820152600d60248201526c53757276657920656e6465642160981b604482015290519081900360640190fd5b336000908152600d60205260409020548111156135c3576040805162461bcd60e51b8152602060048201526013602482015272496e73756666696369656e742066756e64732160681b604482015290519081900360640190fd5b6001546040805163a9059cbb60e01b81523360048201526024810184905290516001600160a01b039092169163a9059cbb916044808201926020929091908290030181600087803b15801561361757600080fd5b505af115801561362b573d6000803e3d6000fd5b505050506040513d602081101561364157600080fd5b5050336000818152600d6020908152604091829020805485900390819055600f80548690039055825185815292519093927fc4e9f6c43fa16caaa3278b92f5fadf533efad8e8124fa4253fd9490cdc0742b492908290030190a25050565b60098054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156109cf5780601f106109a4576101008083540402835291602001916109cf565b8015806137285750336000908152600e6020908152604080832054600d909252909120540115155b613770576040805162461bcd60e51b81526020600482015260146024820152734e6f7468696e6720746f2057697468647261772160601b604482015290519081900360640190fd5b80158061378d57503360009081526011602052604090205460ff16155b6137d4576040805162461bcd60e51b8152602060048201526013602482015272416c726561647920576974686472617765642160681b604482015290519081900360640190fd5b336000908152600e6020908152604080832054600d90925290912054011580159061380f57503360009081526011602052604090205460ff16155b156138c357600154336000818152600e6020908152604080832054600d835281842054825163a9059cbb60e01b81526004810196909652016024850152516001600160a01b039094169363a9059cbb93604480820194918390030190829087803b15801561387c57600080fd5b505af1158015613890573d6000803e3d6000fd5b505050506040513d60208110156138a657600080fd5b5050336000908152601160205260409020805460ff191660011790555b50565b60078054604080516020600260018516156101000260001901909416849004601f810182900482028301820190935282825260609460069361395e93928301828280156139545780601f1061392957610100808354040283529160200191613954565b820191906000526020600020905b81548152906001019060200180831161393757829003601f168201915b5050505050611d1e565b600960405160200180806b1131b7b232a730b6b2911d1160a11b815250600c01858054600181600116156101000203166002900480156139d55780601f106139b35761010080835404028352918201916139d5565b820191906000526020600020905b8154815290600101906020018083116139c1575b5050807411161136b2ba3437b229b4b3b730ba3ab932911d1160591b81525060150184805460018160011615610100020316600290048015613a4e5780601f10613a2c576101008083540402835291820191613a4e565b820191906000526020600020905b815481529060010190602001808311613a3a575b5050807f222c2272657475726e416269506172616d65746572734172726179223a000000815250601d0183805190602001908083835b60208310613aa35780518252601f199092019160209182019101613a84565b6001836020036101000a038019825116818451168082178552505050505050905001806c16113932b83630b1b2b9911d1160991b815250600d0182805460018160011615610100020316600290048015613b345780601f10613b12576101008083540402835291820191613b34565b820191906000526020600020905b815481529060010190602001808311613b20575b5050601160f91b815260408051601e19818403018152600190920190529550505050505090565b6012541580613b7b5750601254600f54108015613b7b5750601254601054105b15613b8557610bce565b6013805460ff19166001179055610bce6109da565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10613bdb57805160ff1916838001178555613c08565b82800160010185558215613c08579182015b82811115613c08578251825591602001919060010190613bed565b50613c14929150613c18565b5090565b6109d791905b80821115613c145760008155600101613c1e56fe566f7465732048617264204361702072656163686564210000000000000000006765744d696e696d756d426c6f636b4e756d626572466f72456d657267656e63795375727665794f6e6c792050726f78792063616e2063616c6c20746869732066756e6374696f6e214f6e6c79204f726967696e616c2050726f78792063616e2063616c6c2074686973206d6574686f64215374696c6c2077616974696e6720666f7220736574436f6c6c61746572616c4461746120746f2062652063616c6c656421537572766579204e6f7420537461727465642100000000000000000000000000736574436f6c6c61746572616c4461746120616c72656164792063616c6c656421a2646970667358221220cc7f3bf856466276233180424b6f508fe3d144c7a0a548366500787677c07fa564736f6c63430006080033
[ 16, 7, 9 ]
0x59dcaa6db5029535004ad5c43eb8febe6ffcf6ed
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); 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) external view returns (uint256); } interface ProtocolAdapter { /** * @dev MUST return "Asset" or "Debt". * SHOULD be implemented by the public constant state variable. */ function adapterType() external pure returns (string memory); /** * @dev MUST return token type (default is "ERC20"). * SHOULD be implemented by the public constant state variable. */ function tokenType() external pure returns (string memory); /** * @dev MUST return amount of the given token locked on the protocol by the given account. */ function getBalance(address token, address account) external view returns (uint256); } interface StakingRewards { function earned(address) external view returns (uint256); } contract PickleStakingV1Adapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant PICKLE = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; address internal constant S_CRV = 0xC25a3A3b969415c80451098fa907EC722572917F; address internal constant PICKLE_POOL = 0xD86F33388BF0bfDF0cCb1ECB4A48a1579504DC0a; /** * @return Amount of staked tokens / claimable rewards for a given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { if (token == PICKLE) { return ERC20(PICKLE_POOL).balanceOf(account); } else if (token == S_CRV) { return StakingRewards(PICKLE_POOL).earned(account); } else { return 0; } } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b91906102f4565b60405180910390f35b610077610072366004610287565b6100c5565b60405161005b9190610365565b61004e61022a565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b600073ffffffffffffffffffffffffffffffffffffffff831673429881672b9ae42b8eba0e26cd9c73711b891ca514156101a0576040517f70a0823100000000000000000000000000000000000000000000000000000000815273d86f33388bf0bfdf0ccb1ecb4a48a1579504dc0a906370a08231906101499085906004016102d3565b60206040518083038186803b15801561016157600080fd5b505afa158015610175573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061019991906102bb565b9050610224565b73ffffffffffffffffffffffffffffffffffffffff831673c25a3a3b969415c80451098fa907ec722572917f1415610220576040517e8cc26200000000000000000000000000000000000000000000000000000000815273d86f33388bf0bfdf0ccb1ecb4a48a1579504dc0a90628cc262906101499085906004016102d3565b5060005b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff8116811461022457600080fd5b60008060408385031215610299578182fd5b6102a38484610263565b91506102b28460208501610263565b90509250929050565b6000602082840312156102cc578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b8181101561032057858101830151858201604001528201610304565b818111156103315783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea26469706673582212200fb2c6a9d833eef70fdfd5ec24015aa7bba97eef9a192c72421300261f0635ca64736f6c63430006050033
[ 38 ]
0x5A99Fa495c894441180113515AAB3B80CE79e491
pragma solidity 0.6.8; 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 vaults 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); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract CryptoPunksMarket { address owner; string public standard = "CryptoPunks"; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply; uint256 public nextPunkIndexToAssign = 0; bool public allPunksAssigned = false; uint256 public punksRemainingToAssign = 0; //mapping (address => uint) public addressToPunkIndex; mapping(uint256 => address) public punkIndexToAddress; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } // A record of punks that are offered for sale at a specific minimum value, and perhaps to a specific person mapping(uint256 => Offer) public punksOfferedForSale; // A record of the highest punk bid mapping(uint256 => Bid) public punkBids; mapping(address => uint256) public pendingWithdrawals; event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); /* Initializes contract with initial supply tokens to the creator of the contract */ constructor() public payable { // balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens owner = msg.sender; totalSupply = 10000; // Update total supply punksRemainingToAssign = totalSupply; name = "CRYPTOPUNKS"; // Set the name for display purposes symbol = "Ͼ"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes } function setInitialOwner(address to, uint256 punkIndex) public { // require(msg.sender == owner, "msg.sender != owner"); require(!allPunksAssigned); require(punkIndex < 10000); if (punkIndexToAddress[punkIndex] != to) { if (punkIndexToAddress[punkIndex] != address(0)) { balanceOf[punkIndexToAddress[punkIndex]]--; } else { punksRemainingToAssign--; } punkIndexToAddress[punkIndex] = to; balanceOf[to]++; emit PunkTransfer(address(0), to, punkIndex); } } function setInitialOwners( address[] memory addresses, uint256[] memory indices ) public { require(msg.sender == owner); uint256 n = addresses.length; for (uint256 i = 0; i < n; i++) { setInitialOwner(addresses[i], indices[i]); } } function allInitialOwnersAssigned() public { require(msg.sender == owner); allPunksAssigned = true; } function getPunk(uint256 punkIndex) public { // require(allPunksAssigned); require(punksRemainingToAssign != 0); require(punkIndexToAddress[punkIndex] == address(0)); require(punkIndex < 10000); punkIndexToAddress[punkIndex] = msg.sender; balanceOf[msg.sender]++; punksRemainingToAssign--; emit Assign(msg.sender, punkIndex); } // Transfer ownership of a punk to another user without requiring payment function transferPunk(address to, uint256 punkIndex) public { // // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); if (punksOfferedForSale[punkIndex].isForSale) { punkNoLongerForSale(punkIndex); } punkIndexToAddress[punkIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; emit Transfer(msg.sender, to, 1); emit PunkTransfer(msg.sender, to, punkIndex); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == to) { // Kill bid and revault value pendingWithdrawals[to] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function punkNoLongerForSale(uint256 punkIndex) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, msg.sender, 0, address(0) ); emit PunkNoLongerForSale(punkIndex); } function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, address(0) ); emit PunkOffered(punkIndex, minSalePriceInWei, address(0)); } function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) public { // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); require(punkIndex < 10000); punksOfferedForSale[punkIndex] = Offer( true, punkIndex, msg.sender, minSalePriceInWei, toAddress ); emit PunkOffered(punkIndex, minSalePriceInWei, toAddress); } function buyPunk(uint256 punkIndex) public payable { // require(allPunksAssigned); Offer storage offer = punksOfferedForSale[punkIndex]; require(punkIndex < 10000); require(offer.isForSale); // punk not actually for sale (offer.onlySellTo == address(0) || offer.onlySellTo == msg.sender); // punk not supposed to be sold to this user require(msg.value >= offer.minValue); // Didn't send enough ETH require(offer.seller == punkIndexToAddress[punkIndex]); // Seller no longer owner of punk address seller = offer.seller; punkIndexToAddress[punkIndex] = msg.sender; balanceOf[seller]--; balanceOf[msg.sender]++; emit Transfer(seller, msg.sender, 1); punkNoLongerForSale(punkIndex); pendingWithdrawals[seller] += msg.value; emit PunkBought(punkIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and revault it. // Any other bid can stay in place. Bid storage bid = punkBids[punkIndex]; if (bid.bidder == msg.sender) { // Kill bid and revault value pendingWithdrawals[msg.sender] += bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); } } function withdraw() public { // require(allPunksAssigned); uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending revault before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } function enterBidForPunk(uint256 punkIndex) public payable { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); require(msg.value != 0); Bid storage existing = punkBids[punkIndex]; require(msg.value > existing.value); if (existing.value > 0) { // Revault the failing bid pendingWithdrawals[existing.bidder] += existing.value; } punkBids[punkIndex] = Bid(true, punkIndex, msg.sender, msg.value); emit PunkBidEntered(punkIndex, msg.value, msg.sender); } function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] == msg.sender); address seller = msg.sender; Bid storage bid = punkBids[punkIndex]; require(bid.value != 0); require(bid.value >= minPrice); punkIndexToAddress[punkIndex] = bid.bidder; balanceOf[seller]--; balanceOf[bid.bidder]++; emit Transfer(seller, bid.bidder, 1); punksOfferedForSale[punkIndex] = Offer( false, punkIndex, bid.bidder, 0, address(0) ); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); pendingWithdrawals[seller] += amount; emit PunkBought(punkIndex, bid.value, seller, bid.bidder); } function withdrawBidForPunk(uint256 punkIndex) public { require(punkIndex < 10000); // require(allPunksAssigned); require(punkIndexToAddress[punkIndex] != address(0)); require(punkIndexToAddress[punkIndex] != msg.sender); Bid storage bid = punkBids[punkIndex]; require(bid.bidder == msg.sender); emit PunkBidWithdrawn(punkIndex, bid.value, msg.sender); uint256 amount = bid.value; punkBids[punkIndex] = Bid(false, punkIndex, address(0), 0); // Revault the bid money msg.sender.transfer(amount); } } 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)); } } interface ICryptoPunksMarket { struct Offer { bool isForSale; uint256 punkIndex; address seller; uint256 minValue; address onlySellTo; } struct Bid { bool hasBid; uint256 punkIndex; address bidder; uint256 value; } event Assign(address indexed to, uint256 punkIndex); event Transfer(address indexed from, address indexed to, uint256 value); event PunkTransfer( address indexed from, address indexed to, uint256 punkIndex ); event PunkOffered( uint256 indexed punkIndex, uint256 minValue, address indexed toAddress ); event PunkBidEntered( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBidWithdrawn( uint256 indexed punkIndex, uint256 value, address indexed fromAddress ); event PunkBought( uint256 indexed punkIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event PunkNoLongerForSale(uint256 indexed punkIndex); function setInitialOwner(address to, uint256 punkIndex) external; function setInitialOwners( address[] calldata addresses, uint256[] calldata indices ) external; function allInitialOwnersAssigned() external; function getPunk(uint256 punkIndex) external; function transferPunk(address to, uint256 punkIndex) external; function punkNoLongerForSale(uint256 punkIndex) external; function offerPunkForSale(uint256 punkIndex, uint256 minSalePriceInWei) external; function offerPunkForSaleToAddress( uint256 punkIndex, uint256 minSalePriceInWei, address toAddress ) external; function buyPunk(uint256 punkIndex) external; function withdraw() external; function enterBidForPunk(uint256 punkIndex) external; function acceptBidForPunk(uint256 punkIndex, uint256 minPrice) external; function withdrawBidForPunk(uint256 punkIndex) external; function punkIndexToAddress(uint256 punkIndex) external returns (address); function punksOfferedForSale(uint256 punkIndex) external returns ( bool isForSale, uint256 _punkIndex, address seller, uint256 minValue, address onlySellTo ); function balanceOf(address user) external returns (uint256); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } interface IPunkToken is IERC20 { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function mint(address to, uint256 amount) external; function changeName(string calldata name) external; function changeSymbol(string calldata symbol) external; function setVaultAddress(address vaultAddress) external; function transferOwnership(address newOwner) external; } 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; } } contract Pausable is Ownable { bool private isPaused = false; event Paused(); event Unpaused(); function getIsPaused() public view returns (bool) { return isPaused; } function pause() public onlyOwner { isPaused = true; } function unpause() public onlyOwner { isPaused = false; } modifier whenPaused { require(isPaused, "Contract is not paused"); _; } modifier whenNotPaused { require(!isPaused, "Contract is paused"); _; } } contract PunkVaultBase is Pausable { address private erc20Address; address private cpmAddress; IPunkToken private erc20; ICryptoPunksMarket private cpm; function getERC20Address() public view returns (address) { return erc20Address; } function getCpmAddress() public view returns (address) { return cpmAddress; } function getERC20() internal view returns (IPunkToken) { return erc20; } function getCPM() internal view returns (ICryptoPunksMarket) { return cpm; } function setERC20Address(address newAddress) internal { require(erc20Address == address(0), "Already initialized ERC20"); erc20Address = newAddress; erc20 = IPunkToken(erc20Address); } function setCpmAddress(address newAddress) internal { require(cpmAddress == address(0), "Already initialized CPM"); cpmAddress = newAddress; cpm = ICryptoPunksMarket(cpmAddress); } } 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 revault on every call to nonReentrant will be lower in // amount. Since revaults 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 revault 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 revault is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub( subtractedValue, "ERC20: decreased allowance below zero" ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds balance" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub( amount, "ERC20: burn amount exceeds balance" ); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } function _changeName(string memory name_) internal { _name = name_; } function _changeSymbol(string memory symbol_) internal { _symbol = symbol_; } /** * @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 {} } abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub( amount, "ERC20: burn amount exceeds allowance" ); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } contract PunkToken is Context, Ownable, ERC20Burnable { address private vaultAddress; constructor(string memory name, string memory symbol) public ERC20(name, symbol) { _mint(msg.sender, 0); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function changeName(string memory name) public onlyOwner { _changeName(name); } function changeSymbol(string memory symbol) public onlyOwner { _changeSymbol(symbol); } function getVaultAddress() public view returns (address) { return vaultAddress; } function setVaultAddress(address newAddress) public onlyOwner { vaultAddress = newAddress; } } contract PunkVaultSafe is PunkVaultBase, ReentrancyGuard { using EnumerableSet for EnumerableSet.UintSet; EnumerableSet.UintSet private reserves; bool private inSafeMode = true; event TokenBurnedSafely(uint256 punkId, address indexed to); function getReserves() internal view returns (EnumerableSet.UintSet storage) { return reserves; } function getInSafeMode() public view returns (bool) { return inSafeMode; } function turnOffSafeMode() public onlyOwner { inSafeMode = false; } function turnOnSafeMode() public onlyOwner { inSafeMode = true; } modifier whenNotInSafeMode { require(!inSafeMode, "Contract is in safe mode"); _; } function simpleRedeem() public whenPaused nonReentrant { require( getERC20().balanceOf(msg.sender) >= 10**18, "ERC20 balance too small" ); require( getERC20().allowance(msg.sender, address(this)) >= 10**18, "ERC20 allowance too small" ); uint256 tokenId = reserves.at(0); getERC20().burnFrom(msg.sender, 10**18); reserves.remove(tokenId); getCPM().transferPunk(msg.sender, tokenId); emit TokenBurnedSafely(tokenId, msg.sender); } } contract Timelocked is PunkVaultSafe { using SafeMath for uint256; enum Timelock {Short, Medium, Long} uint256 private securityLevel; function getSecurityLevel() public view returns (string memory) { if (securityLevel == 0) { return "red"; } else if (securityLevel == 1) { return "orange"; } else if (securityLevel == 2) { return "yellow"; } else { return "green"; } } function increaseSecurityLevel() public onlyOwner { require(securityLevel < 3, "Already max"); securityLevel = securityLevel + 1; } function timeInDays(uint256 num) internal pure returns (uint256) { return num * 60 * 60 * 24; } function getDelay(Timelock lockId) public view returns (uint256) { if (securityLevel == 0) { return 2; // for testing } if (lockId == Timelock.Short) { if (securityLevel == 1) { return timeInDays(1); } else if (securityLevel == 2) { return timeInDays(2); } else { return timeInDays(3); } } else if (lockId == Timelock.Medium) { if (securityLevel == 1) { return timeInDays(2); } else if (securityLevel == 2) { return timeInDays(3); } else { return timeInDays(5); } } else { if (securityLevel == 1) { return timeInDays(3); } else if (securityLevel == 2) { return timeInDays(5); } else { return timeInDays(10); } } } mapping(Timelock => uint256) private releaseTimes; event Locked(Timelock lockId); event UnlockInitiated(Timelock lockId, uint256 whenUnlocked); function getReleaseTime(Timelock lockId) public view returns (uint256) { return releaseTimes[lockId]; } function initiateUnlock(Timelock lockId) public onlyOwner { uint256 newReleaseTime = now.add(getDelay(lockId)); releaseTimes[lockId] = newReleaseTime; emit UnlockInitiated(lockId, newReleaseTime); } function lock(Timelock lockId) public onlyOwner { releaseTimes[lockId] = 0; emit Locked(lockId); } modifier whenNotLockedS { uint256 releaseTime = releaseTimes[Timelock.Short]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedM { uint256 releaseTime = releaseTimes[Timelock.Medium]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } modifier whenNotLockedL { uint256 releaseTime = releaseTimes[Timelock.Long]; require(releaseTime > 0, "Locked"); require(now > releaseTime, "Not unlocked"); _; } } contract Profitable is Timelocked { mapping(address => bool) private verifiedIntegrators; uint256 private numIntegrators = 0; uint256[] private mintFees = [0, 0, 0]; uint256[] private burnFees = [0, 0, 0]; uint256[] private dualFees = [0, 0, 0]; uint256[] private supplierBounty = [(5 * 10**17), 10]; event MintFeesSet(uint256[] mintFees); event BurnFeesSet(uint256[] burnFees); event DualFeesSet(uint256[] dualFees); event SupplierBountySet(uint256[] supplierBounty); event IntegratorSet(address account, bool isVerified); event Withdrawal(address to, uint256 amount); function getMintFees() public view returns (uint256[] memory) { return mintFees; } function getBurnFees() public view returns (uint256[] memory) { return burnFees; } function getDualFees() public view returns (uint256[] memory) { return dualFees; } function getSupplierBounty() public view returns (uint256[] memory) { return supplierBounty; } function _getMintFees() internal view returns (uint256[] storage) { return mintFees; } function _getBurnFees() internal view returns (uint256[] storage) { return burnFees; } function _getDualFees() internal view returns (uint256[] storage) { return dualFees; } function setMintFees(uint256[] memory newMintFees) public onlyOwner whenNotLockedM { require(newMintFees.length == 3, "Wrong length"); mintFees = newMintFees; emit MintFeesSet(newMintFees); } function setBurnFees(uint256[] memory newBurnFees) public onlyOwner whenNotLockedL { require(newBurnFees.length == 3, "Wrong length"); burnFees = newBurnFees; emit BurnFeesSet(newBurnFees); } function setDualFees(uint256[] memory newDualFees) public onlyOwner whenNotLockedM { require(newDualFees.length == 3, "Wrong length"); dualFees = newDualFees; emit DualFeesSet(newDualFees); } function setSupplierBounty(uint256[] memory newSupplierBounty) public onlyOwner whenNotLockedL { require(newSupplierBounty.length == 2, "Wrong length"); supplierBounty = newSupplierBounty; emit SupplierBountySet(newSupplierBounty); } function isIntegrator(address account) public view returns (bool) { return verifiedIntegrators[account]; } function getNumIntegrators() public view returns (uint256) { return numIntegrators; } function setIntegrator(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedIntegrators[account], "Already set"); if (isVerified) { numIntegrators = numIntegrators.add(1); } else { numIntegrators = numIntegrators.sub(1); } verifiedIntegrators[account] = isVerified; emit IntegratorSet(account, isVerified); } function getFee(address account, uint256 numTokens, uint256[] storage fees) internal view returns (uint256) { uint256 fee = 0; if (verifiedIntegrators[account]) { return 0; } else if (numTokens == 1) { fee = fees[0]; } else { fee = fees[1] + numTokens * fees[2]; } return fee; } function getBurnBounty(uint256 numTokens) public view returns (uint256) { uint256 bounty = 0; uint256 reservesLength = getReserves().length(); uint256 padding = supplierBounty[1]; if (reservesLength - numTokens <= padding) { uint256 addedAmount = 0; for (uint256 i = 0; i < numTokens; i++) { if (reservesLength - i <= padding && reservesLength - i > 0) { addedAmount += (supplierBounty[0] * (padding - (reservesLength - i) + 1)); } } bounty += addedAmount; } return bounty; } function getMintBounty(uint256 numTokens) public view returns (uint256) { uint256 bounty = 0; uint256 reservesLength = getReserves().length(); uint256 padding = supplierBounty[1]; if (reservesLength <= padding) { uint256 addedAmount = 0; for (uint256 i = 0; i < numTokens; i++) { if (reservesLength + i <= padding) { addedAmount += (supplierBounty[0] * (padding - (reservesLength + i))); } } bounty += addedAmount; } return bounty; } function withdraw(address payable to) public onlyOwner whenNotLockedM { uint256 balance = address(this).balance; to.transfer(balance); emit Withdrawal(to, balance); } } contract Controllable is Profitable { mapping(address => bool) private verifiedControllers; uint256 private numControllers = 0; event ControllerSet(address account, bool isVerified); event DirectRedemption(uint256 punkId, address by, address indexed to); function isController(address account) public view returns (bool) { return verifiedControllers[account]; } function getNumControllers() public view returns (uint256) { return numControllers; } function setController(address account, bool isVerified) public onlyOwner whenNotLockedM { require(isVerified != verifiedControllers[account], "Already set"); if (isVerified) { numControllers++; } else { numControllers--; } verifiedControllers[account] = isVerified; emit ControllerSet(account, isVerified); } modifier onlyController() { require(isController(_msgSender()), "Not a controller"); _; } function directRedeem(uint256 tokenId, address to) public onlyController { require(getERC20().balanceOf(to) >= 10**18, "ERC20 balance too small"); bool toSelf = (to == address(this)); require( toSelf || (getERC20().allowance(to, address(this)) >= 10**18), "ERC20 allowance too small" ); require(getReserves().contains(tokenId), "Not in holdings"); getERC20().burnFrom(to, 10**18); getReserves().remove(tokenId); if (!toSelf) { getCPM().transferPunk(to, tokenId); } emit DirectRedemption(tokenId, _msgSender(), to); } } contract Randomizable is Controllable { uint256 private randNonce = 0; function getPseudoRand(uint256 modulus) internal returns (uint256) { randNonce = randNonce.add(1); return uint256(keccak256(abi.encodePacked(now, _msgSender(), randNonce))) % modulus; } } contract Manageable is Randomizable { event MigrationComplete(address to); event TokenNameChange(string name); event TokenSymbolChange(string symbol); function migrate(address to, uint256 max) public onlyOwner whenNotLockedL { uint256 count = 0; uint256 reservesLength = getReserves().length(); for (uint256 i = 0; i < reservesLength; i++) { if (count >= max) { return; } uint256 tokenId = getReserves().at(0); getCPM().transferPunk(to, tokenId); getReserves().remove(tokenId); count = count.add(1); } getERC20().transferOwnership(to); emit MigrationComplete(to); } function changeTokenName(string memory newName) public onlyOwner whenNotLockedM { getERC20().changeName(newName); emit TokenNameChange(newName); } function changeTokenSymbol(string memory newSymbol) public onlyOwner whenNotLockedM { getERC20().changeSymbol(newSymbol); emit TokenSymbolChange(newSymbol); } function setReverseLink() public onlyOwner { getERC20().setVaultAddress(address(this)); } } contract PunkVault is Manageable { event TokenMinted(uint256 tokenId, address indexed to); event TokensMinted(uint256[] tokenIds, address indexed to); event TokenBurned(uint256 tokenId, address indexed to); event TokensBurned(uint256[] tokenIds, address indexed to); constructor(address erc20Address, address cpmAddress) public { setERC20Address(erc20Address); setCpmAddress(cpmAddress); } function getCryptoPunkAtIndex(uint256 index) public view returns (uint256) { return getReserves().at(index); } function getReservesLength() public view returns (uint256) { return getReserves().length(); } function isCryptoPunkDeposited(uint256 tokenId) public view returns (bool) { return getReserves().contains(tokenId); } function mintPunk(uint256 tokenId) public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getMintFees()); uint256 bounty = getMintBounty(1); if (fee > bounty) { uint256 differnce = fee.sub(bounty); require(msg.value >= differnce, "Value too low"); } bool success = _mintPunk(tokenId, false); if (success && bounty > fee) { uint256 difference = bounty.sub(fee); uint256 balance = address(this).balance; address payable sender = _msgSender(); if (balance >= difference) { sender.transfer(difference); } else { sender.transfer(balance); } } } function _mintPunk(uint256 tokenId, bool partOfDualOp) private returns (bool) { address msgSender = _msgSender(); require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); require(_tokenId == tokenId, "Wrong punk"); require(forSale, "Punk not available"); require(buyer == address(this), "Transfer not approved"); require(minVal == 0, "Min value not zero"); require(msgSender == seller, "Sender is not seller"); require( msgSender == getCPM().punkIndexToAddress(tokenId), "Sender is not owner" ); getCPM().buyPunk(tokenId); getReserves().add(tokenId); if (!partOfDualOp) { uint256 tokenAmount = 10**18; getERC20().mint(msgSender, tokenAmount); } emit TokenMinted(tokenId, _msgSender()); return true; } function mintPunkMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), tokenIds.length, _getMintFees()); uint256 bounty = getMintBounty(tokenIds.length); require(bounty >= fee || msg.value >= fee.sub(bounty), "Value too low"); uint256 numTokens = _mintPunkMultiple(tokenIds, false); require(numTokens > 0, "No tokens minted"); require(numTokens == tokenIds.length, "Untransferable punks"); if (fee > bounty) { uint256 differnce = fee.sub(bounty); require(msg.value >= differnce, "Value too low"); } if (bounty > fee) { uint256 difference = bounty.sub(fee); uint256 balance = address(this).balance; address payable sender = _msgSender(); if (balance >= difference) { sender.transfer(difference); } else { sender.transfer(balance); } } } function _mintPunkMultiple(uint256[] memory tokenIds, bool partOfDualOp) private returns (uint256) { require(tokenIds.length > 0, "No tokens"); require(tokenIds.length <= 100, "Over 100 tokens"); uint256[] memory newTokenIds = new uint256[](tokenIds.length); uint256 numNewTokens = 0; address msgSender = _msgSender(); for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(tokenId < 10000, "tokenId too high"); (bool forSale, uint256 _tokenId, address seller, uint256 minVal, address buyer) = getCPM() .punksOfferedForSale(tokenId); bool rightToken = _tokenId == tokenId; bool isApproved = buyer == address(this); bool priceIsZero = minVal == 0; bool isSeller = msgSender == seller; bool isOwner = msgSender == getCPM().punkIndexToAddress(tokenId); if ( forSale && rightToken && isApproved && priceIsZero && isSeller && isOwner ) { getCPM().buyPunk(tokenId); getReserves().add(tokenId); newTokenIds[numNewTokens] = tokenId; numNewTokens = numNewTokens.add(1); } } if (numNewTokens > 0) { if (!partOfDualOp) { uint256 tokenAmount = numNewTokens * (10**18); getERC20().mint(msgSender, tokenAmount); } emit TokensMinted(newTokenIds, msgSender); } return numNewTokens; } function redeemPunk() public payable nonReentrant whenNotPaused { uint256 fee = getFee(_msgSender(), 1, _getBurnFees()) + getBurnBounty(1); require(msg.value >= fee, "Value too low"); _redeemPunk(false); } function _redeemPunk(bool partOfDualOp) private { address msgSender = _msgSender(); uint256 tokenAmount = 10**18; require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); emit TokenBurned(tokenId, msgSender); } function redeemPunkMultiple(uint256 numTokens) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), numTokens, _getBurnFees()) + getBurnBounty(numTokens); require(msg.value >= fee, "Value too low"); _redeemPunkMultiple(numTokens, false); } function _redeemPunkMultiple(uint256 numTokens, bool partOfDualOp) private { require(numTokens > 0, "No tokens"); require(numTokens <= 100, "Over 100 tokens"); address msgSender = _msgSender(); uint256 tokenAmount = numTokens * (10**18); require( partOfDualOp || (getERC20().balanceOf(msgSender) >= tokenAmount), "ERC20 balance too small" ); require( partOfDualOp || (getERC20().allowance(msgSender, address(this)) >= tokenAmount), "ERC20 allowance too small" ); if (!partOfDualOp) { getERC20().burnFrom(msgSender, tokenAmount); } uint256[] memory tokenIds = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); tokenIds[i] = tokenId; getReserves().remove(tokenId); getCPM().transferPunk(msgSender, tokenId); } emit TokensBurned(tokenIds, msgSender); } function mintAndRedeem(uint256 tokenId) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 fee = getFee(_msgSender(), 1, _getDualFees()); require(msg.value >= fee, "Value too low"); require(_mintPunk(tokenId, true), "Minting failed"); _redeemPunk(true); } function mintAndRedeemMultiple(uint256[] memory tokenIds) public payable nonReentrant whenNotPaused whenNotInSafeMode { uint256 numTokens = tokenIds.length; require(numTokens > 0, "No tokens"); require(numTokens <= 20, "Over 20 tokens"); uint256 fee = getFee(_msgSender(), numTokens, _getDualFees()); require(msg.value >= fee, "Value too low"); uint256 numTokensMinted = _mintPunkMultiple(tokenIds, true); if (numTokensMinted > 0) { _redeemPunkMultiple(numTokens, true); } } function mintRetroactively(uint256 tokenId, address to) public onlyOwner whenNotLockedS { require( getCPM().punkIndexToAddress(tokenId) == address(this), "Not owner" ); require(!getReserves().contains(tokenId), "Already in reserves"); uint256 cryptoPunkBalance = getCPM().balanceOf(address(this)); require( (getERC20().totalSupply() / (10**18)) < cryptoPunkBalance, "No excess NFTs" ); getReserves().add(tokenId); getERC20().mint(to, 10**18); emit TokenMinted(tokenId, _msgSender()); } function redeemRetroactively(address to) public onlyOwner whenNotLockedS { require( getERC20().balanceOf(address(this)) >= (10**18), "Not enough PUNK" ); getERC20().burn(10**18); uint256 reservesLength = getReserves().length(); uint256 randomIndex = getPseudoRand(reservesLength); uint256 tokenId = getReserves().at(randomIndex); getReserves().remove(tokenId); getCPM().transferPunk(to, tokenId); emit TokenBurned(tokenId, _msgSender()); } }
0x6080604052600436106102e45760003560e01c80638da5cb5b11610190578063c73cce39116100dc578063f2a6f21511610095578063fa70c3021161006f578063fa70c30214610ddd578063fb15298d14610e67578063fb34499d14610ea0578063fc9d015414610ecd576102e4565b8063f2a6f21514610d80578063f2fde38b14610d95578063f338fc1914610dc8576102e4565b8063c73cce3914610af8578063cf43cd6d14610ba6578063cf97174814610c54578063e0dba60f14610cf5578063e63b094014610d30578063f055c9a014610d45576102e4565b8063a70e81fd11610149578063b429afeb11610123578063b429afeb146109ea578063b9f890de14610a1d578063c2c0d41814610a32578063c6d3ab9d14610a47576102e4565b8063a70e81fd146108eb578063ad68ebf714610900578063b0018bfc14610939576102e4565b80638da5cb5b1461079657806397a6d274146107ab5780639cd7d766146107de5780639f3d4e691461088c5780639f92b09b146108b9578063a2be5a1f146108e3576102e4565b80635395b7021161024f5780637fc72e75116102085780638456cb59116101e25780638456cb591461066f57806386a206e4146106845780638985a3f0146106b557806389caf16d14610763576102e4565b80637fc72e75146105f0578063824580b314610619578063830ddb9714610652576102e4565b80635395b7021461054a5780635ea0fa041461055f578063715018a61461057c57806372e0dbd41461059157806372f9c421146105ae5780637af9bc02146105db576102e4565b80633f4ba83a116102a15780633f4ba83a146104845780634110a9f5146104995780634116c0e3146104c35780634ad4f87c146104ed57806350018eff1461050257806351cff8d914610517576102e4565b80630bdf02bd146102e95780632361741e146103285780632753167b1461038d57806331f8a39d146103a257806334d9d89c146104455780633e8354f01461046f575b600080fd5b3480156102f557600080fd5b506103166004803603602081101561030c57600080fd5b503560ff16610ee2565b60408051918252519081900360200190f35b34801561033457600080fd5b5061033d610f16565b60408051602080825283518183015283519192839290830191858101910280838360005b83811015610379578181015183820152602001610361565b505050509050019250505060405180910390f35b34801561039957600080fd5b5061033d610f6f565b610443600480360360208110156103b857600080fd5b810190602081018135600160201b8111156103d257600080fd5b8201836020820111156103e457600080fd5b803590602001918460208302840111600160201b8311171561040557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550610fc5945050505050565b005b34801561045157600080fd5b506103166004803603602081101561046857600080fd5b50356112fb565b34801561047b57600080fd5b5061044361131b565b34801561049057600080fd5b506104436113c3565b3480156104a557600080fd5b50610316600480360360208110156104bc57600080fd5b503561142a565b3480156104cf57600080fd5b50610316600480360360208110156104e657600080fd5b50356114ca565b3480156104f957600080fd5b50610316611540565b34801561050e57600080fd5b5061033d611546565b34801561052357600080fd5b506104436004803603602081101561053a57600080fd5b50356001600160a01b031661159c565b34801561055657600080fd5b5061031661170e565b6104436004803603602081101561057557600080fd5b5035611714565b34801561058857600080fd5b506104436118c4565b610443600480360360208110156105a757600080fd5b5035611966565b3480156105ba57600080fd5b50610316600480360360208110156105d157600080fd5b503560ff16611aca565b3480156105e757600080fd5b50610443611baa565b3480156105fc57600080fd5b50610605611f65565b604080519115158252519081900360200190f35b34801561062557600080fd5b506104436004803603604081101561063c57600080fd5b50803590602001356001600160a01b0316611f6e565b6104436004803603602081101561066857600080fd5b503561236b565b34801561067b57600080fd5b506104436124c6565b34801561069057600080fd5b50610699612533565b604080516001600160a01b039092168252519081900360200190f35b3480156106c157600080fd5b50610443600480360360208110156106d857600080fd5b810190602081018135600160201b8111156106f257600080fd5b82018360208201111561070457600080fd5b803590602001918460208302840111600160201b8311171561072557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612542945050505050565b34801561076f57600080fd5b506104436004803603602081101561078657600080fd5b50356001600160a01b0316612704565b3480156107a257600080fd5b50610699612a50565b3480156107b757600080fd5b50610605600480360360208110156107ce57600080fd5b50356001600160a01b0316612a5f565b3480156107ea57600080fd5b506104436004803603602081101561080157600080fd5b810190602081018135600160201b81111561081b57600080fd5b82018360208201111561082d57600080fd5b803590602001918460208302840111600160201b8311171561084e57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550612a7d945050505050565b34801561089857600080fd5b50610443600480360360208110156108af57600080fd5b503560ff16612c34565b3480156108c557600080fd5b50610605600480360360208110156108dc57600080fd5b5035612d03565b610443612d11565b3480156108f757600080fd5b50610443612e2b565b34801561090c57600080fd5b506104436004803603604081101561092357600080fd5b506001600160a01b038135169060200135612efc565b34801561094557600080fd5b506104436004803603602081101561095c57600080fd5b810190602081018135600160201b81111561097657600080fd5b82018360208201111561098857600080fd5b803590602001918460018302840111600160201b831117156109a957600080fd5b91908080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525092955061319e945050505050565b3480156109f657600080fd5b5061060560048036036020811015610a0d57600080fd5b50356001600160a01b03166133f2565b348015610a2957600080fd5b50610699613410565b348015610a3e57600080fd5b5061031661341f565b348015610a5357600080fd5b5061044360048036036020811015610a6a57600080fd5b810190602081018135600160201b811115610a8457600080fd5b820183602082011115610a9657600080fd5b803590602001918460018302840111600160201b83111715610ab757600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550613431945050505050565b348015610b0457600080fd5b5061044360048036036020811015610b1b57600080fd5b810190602081018135600160201b811115610b3557600080fd5b820183602082011115610b4757600080fd5b803590602001918460208302840111600160201b83111715610b6857600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550613643945050505050565b348015610bb257600080fd5b5061044360048036036020811015610bc957600080fd5b810190602081018135600160201b811115610be357600080fd5b820183602082011115610bf557600080fd5b803590602001918460208302840111600160201b83111715610c1657600080fd5b9190808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152509295506137e8945050505050565b61044360048036036020811015610c6a57600080fd5b810190602081018135600160201b811115610c8457600080fd5b820183602082011115610c9657600080fd5b803590602001918460208302840111600160201b83111715610cb757600080fd5b91908080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525092955061399f945050505050565b348015610d0157600080fd5b5061044360048036036040811015610d1857600080fd5b506001600160a01b0381351690602001351515613b95565b348015610d3c57600080fd5b50610443613d6b565b348015610d5157600080fd5b5061044360048036036040811015610d6857600080fd5b506001600160a01b0381351690602001351515613dcf565b348015610d8c57600080fd5b50610605613fc0565b348015610da157600080fd5b5061044360048036036020811015610db857600080fd5b50356001600160a01b0316613fd0565b348015610dd457600080fd5b5061033d6140c8565b348015610de957600080fd5b50610df261411e565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610e2c578181015183820152602001610e14565b50505050905090810190601f168015610e595780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610e7357600080fd5b5061044360048036036040811015610e8a57600080fd5b50803590602001356001600160a01b03166141c9565b348015610eac57600080fd5b5061044360048036036020811015610ec357600080fd5b503560ff1661461d565b348015610ed957600080fd5b50610443614711565b6000600a6000836002811115610ef457fe5b6002811115610eff57fe5b81526020019081526020016000205490505b919050565b6060600e805480602002602001604051908101604052809291908181526020018280548015610f6457602002820191906000526020600020905b815481526020019060010190808311610f50575b505050505090505b90565b6060600f805480602002602001604051908101604052809291908181526020018280548015610f645760200282019190600052602060002090815481526020019060010190808311610f50575050505050905090565b6002600554141561100b576040805162461bcd60e51b815260206004820152601f6024820152600080516020615d82833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615611064576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff16156110b7576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b60006110d36110c4614778565b83516110ce61477c565b614781565b905060006110e183516114ca565b9050818110158061110157506110fd828263ffffffff61481616565b3410155b611142576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b600061114f846000614858565b905060008111611199576040805162461bcd60e51b815260206004820152601060248201526f139bc81d1bdad95b9cc81b5a5b9d195960821b604482015290519081900360640190fd5b835181146111e5576040805162461bcd60e51b8152602060048201526014602482015273556e7472616e7366657261626c652070756e6b7360601b604482015290519081900360640190fd5b818311156112485760006111ff848463ffffffff61481616565b905080341015611246576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b505b828211156112f0576000611262838563ffffffff61481616565b905047600061126f614778565b90508282106112b4576040516001600160a01b0382169084156108fc029085906000818181858888f193505050501580156112ae573d6000803e3d6000fd5b506112ec565b6040516001600160a01b0382169083156108fc029084906000818181858888f193505050501580156112ea573d6000803e3d6000fd5b505b5050505b505060016005555050565b600061131582611309614cf8565b9063ffffffff614cfd16565b92915050565b611323614778565b6000546001600160a01b03908116911614611373576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6003600954106113b8576040805162461bcd60e51b815260206004820152600b60248201526a082d8e4cac2c8f240dac2f60ab1b604482015290519081900360640190fd5b600980546001019055565b6113cb614778565b6000546001600160a01b0390811691161461141b576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6000805460ff60a01b19169055565b6000808061143e611439614cf8565b614d09565b90506000601060018154811061145057fe5b9060005260206000200154905080858303116114c1576000805b868110156114ba57828185031115801561148657506000818503115b156114b257808403830360010160106000815481106114a157fe5b906000526020600020015402820191505b60010161146a565b5092909201915b50909392505050565b600080806114d9611439614cf8565b9050600060106001815481106114eb57fe5b906000526020600020015490508082116114c1576000805b868110156114ba578281850111611538578084018303601060008154811061152757fe5b906000526020600020015402820191505b600101611503565b600c5490565b60606010805480602002602001604051908101604052809291908181526020018280548015610f645760200282019190600052602060002090815481526020019060010190808311610f50575050505050905090565b6115a4614778565b6000546001600160a01b039081169116146115f4576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615de88339815191525480611649576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b80421161168c576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b60405147906001600160a01b0384169082156108fc029083906000818181858888f193505050501580156116c4573d6000803e3d6000fd5b50604080516001600160a01b03851681526020810183905281517f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b65929181900390910190a1505050565b60125490565b6002600554141561175a576040805162461bcd60e51b815260206004820152601f6024820152600080516020615d82833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff16156117b3576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff1615611806576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b600061181d611813614778565b60016110ce614d14565b905080341015611864576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b61186f826001614d19565b6118b1576040805162461bcd60e51b815260206004820152600e60248201526d135a5b9d1a5b99c819985a5b195960921b604482015290519081900360640190fd5b6118bb60016151bb565b50506001600555565b6118cc614778565b6000546001600160a01b0390811691161461191c576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b600080546040516001600160a01b03909116907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3600080546001600160a01b0319169055565b600260055414156119ac576040805162461bcd60e51b815260206004820152601f6024820152600080516020615d82833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615611a05576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff1615611a58576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b6000611a638261142a565b611a77611a6e614778565b846110ce615510565b01905080341015611abf576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b6118bb826000615515565b600060095460001415611adf57506002610f11565b6000826002811115611aed57fe5b1415611b2e5760095460011415611b0f57611b0860016159ae565b9050610f11565b60095460021415611b2457611b0860026159ae565b611b0860036159ae565b6001826002811115611b3c57fe5b1415611b765760095460011415611b5757611b0860026159ae565b60095460021415611b6c57611b0860036159ae565b611b0860056159ae565b60095460011415611b8b57611b0860036159ae565b60095460021415611ba057611b0860056159ae565b611b08600a6159ae565b600054600160a01b900460ff16611c01576040805162461bcd60e51b815260206004820152601660248201527510dbdb9d1c9858dd081a5cc81b9bdd081c185d5cd95960521b604482015290519081900360640190fd5b60026005541415611c47576040805162461bcd60e51b815260206004820152601f6024820152600080516020615d82833981519152604482015290519081900360640190fd5b6002600555670de0b6b3a7640000611c5d6159b6565b6001600160a01b03166370a08231336040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b158015611cb257600080fd5b505afa158015611cc6573d6000803e3d6000fd5b505050506040513d6020811015611cdc57600080fd5b50511015611d2b576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b670de0b6b3a7640000611d3c6159b6565b60408051636eb1769f60e11b815233600482015230602482015290516001600160a01b03929092169163dd62ed3e91604480820192602092909190829003018186803b158015611d8b57600080fd5b505afa158015611d9f573d6000803e3d6000fd5b505050506040513d6020811015611db557600080fd5b50511015611e06576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b6000611e1960068263ffffffff614cfd16565b9050611e236159b6565b6040805163079cc67960e41b8152336004820152670de0b6b3a7640000602482015290516001600160a01b0392909216916379cc67909160448082019260009290919082900301818387803b158015611e7b57600080fd5b505af1158015611e8f573d6000803e3d6000fd5b50505050611ea78160066159c590919063ffffffff16565b50611eb06159d1565b6001600160a01b0316638b72a2ec33836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015611f0f57600080fd5b505af1158015611f23573d6000803e3d6000fd5b50506040805184815290513393507f8b309647fdd65a5ccf8e22445d08d0c72aca99f0674013717bb2fde8d64709ae92509081900360200190a2506001600555565b60085460ff1690565b611f7e611f79614778565b6133f2565b611fc2576040805162461bcd60e51b815260206004820152601060248201526f2737ba10309031b7b73a3937b63632b960811b604482015290519081900360640190fd5b670de0b6b3a7640000611fd36159b6565b6001600160a01b03166370a08231836040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561202857600080fd5b505afa15801561203c573d6000803e3d6000fd5b505050506040513d602081101561205257600080fd5b505110156120a1576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b6001600160a01b038116301480806121455750670de0b6b3a76400006120c56159b6565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b15801561211657600080fd5b505afa15801561212a573d6000803e3d6000fd5b505050506040513d602081101561214057600080fd5b505110155b612192576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b6121aa8361219e614cf8565b9063ffffffff6159e016565b6121ed576040805162461bcd60e51b815260206004820152600f60248201526e4e6f7420696e20686f6c64696e677360881b604482015290519081900360640190fd5b6121f56159b6565b6001600160a01b03166379cc679083670de0b6b3a76400006040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561225c57600080fd5b505af1158015612270573d6000803e3d6000fd5b5050505061228c83612280614cf8565b9063ffffffff6159c516565b50806123125761229a6159d1565b6001600160a01b0316638b72a2ec83856040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156122f957600080fd5b505af115801561230d573d6000803e3d6000fd5b505050505b816001600160a01b03167f797bd1463a543a5fb696ff9b9d3340b0bef8762932107d896f055b77e4d93d4b84612346614778565b604080519283526001600160a01b0390911660208301528051918290030190a2505050565b600260055414156123b1576040805162461bcd60e51b815260206004820152601f6024820152600080516020615d82833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff161561240a576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b6000612421612417614778565b60016110ce61477c565b9050600061242f60016114ca565b90508082111561249457600061244b838363ffffffff61481616565b905080341015612492576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b505b60006124a1846000614d19565b90508080156124af57508282115b156112f0576000611262838563ffffffff61481616565b6124ce614778565b6000546001600160a01b0390811691161461251e576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6000805460ff60a01b1916600160a01b179055565b6002546001600160a01b031690565b61254a614778565b6000546001600160a01b0390811691161461259a576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615de883398151915254806125ef576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612632576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600314612677576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b815161268a90600f906020850190615cfa565b507f556290bdbad25e439ee0740de619ad1d21a711a9f3c21030bdaffbfb9b679e15826040518080602001828103825283818151815260200191508051906020019060200280838360005b838110156126ed5781810151838201526020016126d5565b505050509050019250505060405180910390a15050565b61270c614778565b6000546001600160a01b0390811691161461275c576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b60008052600a6020527f13da86008ba1c6922daee3e07db95305ef49ebced9f5467a0b8613fcc6b343e354806127c2576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612805576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b670de0b6b3a76400006128166159b6565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561286b57600080fd5b505afa15801561287f573d6000803e3d6000fd5b505050506040513d602081101561289557600080fd5b505110156128dc576040805162461bcd60e51b815260206004820152600f60248201526e4e6f7420656e6f7567682050554e4b60881b604482015290519081900360640190fd5b6128e46159b6565b6001600160a01b03166342966c68670de0b6b3a76400006040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b15801561293157600080fd5b505af1158015612945573d6000803e3d6000fd5b505050506000612956611439614cf8565b90506000612963826159ec565b9050600061297382611309614cf8565b905061298181612280614cf8565b5061298a6159d1565b6001600160a01b0316638b72a2ec86836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156129e957600080fd5b505af11580156129fd573d6000803e3d6000fd5b50505050612a09614778565b6001600160a01b03167f33631bcd0a4d34a7e2c240ab0753d5adfb7284d8ac89dab6876ec785c0cfa0e6826040518082815260200191505060405180910390a25050505050565b6000546001600160a01b031690565b6001600160a01b03166000908152600b602052604090205460ff1690565b612a85614778565b6000546001600160a01b03908116911614612ad5576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba85480612b3c576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612b7f576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600214612bc4576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b8151612bd7906010906020850190615cfa565b5060408051602080825284518183015284517fbbfba7b79c4ec17454bfb989aaa624c5de83143861bb0c1139da4f3b4b0a9f0d938693928392918301918186019102808383600083156126ed5781810151838201526020016126d5565b612c3c614778565b6000546001600160a01b03908116911614612c8c576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6000600a6000836002811115612c9e57fe5b6002811115612ca957fe5b8152602001908152602001600020819055507feee8c9a7b7852b972adec4c62096923d399a82270752d09060dd7ad07f39e3f98160405180826002811115612ced57fe5b60ff16815260200191505060405180910390a150565b60006113158261219e614cf8565b60026005541415612d57576040805162461bcd60e51b815260206004820152601f6024820152600080516020615d82833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615612db0576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b6000612dbc600161142a565b612dd1612dc7614778565b60016110ce615510565b01905080341015612e19576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b612e2360006151bb565b506001600555565b612e33614778565b6000546001600160a01b03908116911614612e83576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b612e8b6159b6565b6001600160a01b03166385535cc5306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050600060405180830381600087803b158015612ee257600080fd5b505af1158015612ef6573d6000803e3d6000fd5b50505050565b612f04614778565b6000546001600160a01b03908116911614612f54576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba85480612fbb576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211612ffe576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b60008061300c611439614cf8565b905060005b818110156130e15784831061302857505050613199565b60006130376000611309614cf8565b90506130416159d1565b6001600160a01b0316638b72a2ec88836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156130a057600080fd5b505af11580156130b4573d6000803e3d6000fd5b505050506130c481612280614cf8565b506130d684600163ffffffff615a6d16565b935050600101613011565b506130ea6159b6565b6001600160a01b031663f2fde38b866040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050600060405180830381600087803b15801561314157600080fd5b505af1158015613155573d6000803e3d6000fd5b5050604080516001600160a01b038916815290517f6bc1a05a654a49243059be717e63e5e5a88fbb66af7093577daf9a27390722d19350908190036020019150a150505b505050565b6131a6614778565b6000546001600160a01b039081169116146131f6576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615de8833981519152548061324b576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b80421161328e576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6132966159b6565b6001600160a01b0316635353a2d8836040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156132f15781810151838201526020016132d9565b50505050905090810190601f16801561331e5780820380516001836020036101000a031916815260200191505b5092505050600060405180830381600087803b15801561333d57600080fd5b505af1158015613351573d6000803e3d6000fd5b505050507f67c5eb670df7ec2c03a007ee155f462522e530d090c943b70c4eaa5656e0b7c6826040518080602001828103825283818151815260200191508051906020019080838360005b838110156133b457818101518382015260200161339c565b50505050905090810190601f1680156133e15780820380516001836020036101000a031916815260200191505b509250505060405180910390a15050565b6001600160a01b031660009081526011602052604090205460ff1690565b6001546001600160a01b031690565b600061342c611439614cf8565b905090565b613439614778565b6000546001600160a01b03908116911614613489576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615de883398151915254806134de576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613521576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6135296159b6565b6001600160a01b031663a3895fff836040518263ffffffff1660e01b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561358457818101518382015260200161356c565b50505050905090810190601f1680156135b15780820380516001836020036101000a031916815260200191505b5092505050600060405180830381600087803b1580156135d057600080fd5b505af11580156135e4573d6000803e3d6000fd5b505060408051602080825286518183015286517f773ec0a6b643b90e0a49ac87584faa630abb0d1fa9bfe5d589918b6e33afbacf95508794509192839290830191850190808383600083156133b457818101518382015260200161339c565b61364b614778565b6000546001600160a01b0390811691161461369b576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615de883398151915254806136f0576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613733576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b8151600314613778576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b815161378b90600d906020850190615cfa565b5060408051602080825284518183015284517ff9a8325633515ac20c4c12c09c48b1655bbe4a70f5ac29bd1f85803ef8a3be35938693928392918301918186019102808383600083156126ed5781810151838201526020016126d5565b6137f0614778565b6000546001600160a01b03908116911614613840576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6002600052600a6020527fbff4442b8ed600beeb8e26b1279a0f0d14c6edfaec26d968ee13c86f7d4c2ba854806138a7576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116138ea576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b815160031461392f576040805162461bcd60e51b815260206004820152600c60248201526b0aee4dedcce40d8cadccee8d60a31b604482015290519081900360640190fd5b815161394290600e906020850190615cfa565b5060408051602080825284518183015284517fb1aecf0a8e6c83b5d243952384b0db2688bccb20ac76e4ced69a1e13f6a73d2f938693928392918301918186019102808383600083156126ed5781810151838201526020016126d5565b600260055414156139e5576040805162461bcd60e51b815260206004820152601f6024820152600080516020615d82833981519152604482015290519081900360640190fd5b6002600555600054600160a01b900460ff1615613a3e576040805162461bcd60e51b815260206004820152601260248201527110dbdb9d1c9858dd081a5cc81c185d5cd95960721b604482015290519081900360640190fd5b60085460ff1615613a91576040805162461bcd60e51b8152602060048201526018602482015277436f6e747261637420697320696e2073616665206d6f646560401b604482015290519081900360640190fd5b805180613ad1576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b6014811115613b18576040805162461bcd60e51b815260206004820152600e60248201526d4f76657220323020746f6b656e7360901b604482015290519081900360640190fd5b6000613b2e613b25614778565b836110ce614d14565b905080341015613b75576040805162461bcd60e51b815260206004820152600d60248201526c56616c756520746f6f206c6f7760981b604482015290519081900360640190fd5b6000613b82846001614858565b905080156112f0576112f0836001615515565b613b9d614778565b6000546001600160a01b03908116911614613bed576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615de88339815191525480613c42576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613c85576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6001600160a01b03831660009081526011602052604090205460ff1615158215151415613ce7576040805162461bcd60e51b815260206004820152600b60248201526a105b1c9958591e481cd95d60aa1b604482015290519081900360640190fd5b8115613cfb57601280546001019055613d06565b601280546000190190555b6001600160a01b038316600081815260116020908152604091829020805460ff191686151590811790915582519384529083015280517f9c1e55b2ea976b1ce106746d9325847e838c89adca542764df43b80cadb59b049281900390910190a1505050565b613d73614778565b6000546001600160a01b03908116911614613dc3576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6008805460ff19169055565b613dd7614778565b6000546001600160a01b03908116911614613e27576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600052600a602052600080516020615de88339815191525480613e7c576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b804211613ebf576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b6001600160a01b0383166000908152600b602052604090205460ff1615158215151415613f21576040805162461bcd60e51b815260206004820152600b60248201526a105b1c9958591e481cd95d60aa1b604482015290519081900360640190fd5b8115613f4357600c54613f3b90600163ffffffff615a6d16565b600c55613f5b565b600c54613f5790600163ffffffff61481616565b600c555b6001600160a01b0383166000818152600b6020908152604091829020805460ff191686151590811790915582519384529083015280517f99042b85468bcc9210d26d97ff0ec84ccc48b4bc7dc16f8bc4a35c3d769cad939281900390910190a1505050565b600054600160a01b900460ff1690565b613fd8614778565b6000546001600160a01b03908116911614614028576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6001600160a01b03811661406d5760405162461bcd60e51b8152600401808060200182810382526026815260200180615da26026913960400191505060405180910390fd5b600080546040516001600160a01b03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b0319166001600160a01b0392909216919091179055565b6060600d805480602002602001604051908101604052809291908181526020018280548015610f645760200282019190600052602060002090815481526020019060010190808311610f50575050505050905090565b60606009546000141561414b57506040805180820190915260038152621c995960ea1b6020820152610f6c565b6009546001141561417957506040805180820190915260068152656f72616e676560d01b6020820152610f6c565b600954600214156141a7575060408051808201909152600681526579656c6c6f7760d01b6020820152610f6c565b5060408051808201909152600581526433b932b2b760d91b6020820152610f6c565b6141d1614778565b6000546001600160a01b03908116911614614221576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b60008052600a6020527f13da86008ba1c6922daee3e07db95305ef49ebced9f5467a0b8613fcc6b343e35480614287576040805162461bcd60e51b8152602060048201526006602482015265131bd8dad95960d21b604482015290519081900360640190fd5b8042116142ca576040805162461bcd60e51b815260206004820152600c60248201526b139bdd081d5b9b1bd8dad95960a21b604482015290519081900360640190fd5b306142d36159d1565b6001600160a01b03166358178168856040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b15801561431857600080fd5b505af115801561432c573d6000803e3d6000fd5b505050506040513d602081101561434257600080fd5b50516001600160a01b03161461438b576040805162461bcd60e51b81526020600482015260096024820152682737ba1037bbb732b960b91b604482015290519081900360640190fd5b6143978361219e614cf8565b156143df576040805162461bcd60e51b8152602060048201526013602482015272416c726561647920696e20726573657276657360681b604482015290519081900360640190fd5b60006143e96159d1565b6001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b03168152602001915050602060405180830381600087803b15801561444057600080fd5b505af1158015614454573d6000803e3d6000fd5b505050506040513d602081101561446a57600080fd5b5051905080670de0b6b3a76400006144806159b6565b6001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156144b857600080fd5b505afa1580156144cc573d6000803e3d6000fd5b505050506040513d60208110156144e257600080fd5b5051816144eb57fe5b041061452f576040805162461bcd60e51b815260206004820152600e60248201526d4e6f20657863657373204e46547360901b604482015290519081900360640190fd5b6145478461453b614cf8565b9063ffffffff615ac716565b506145506159b6565b6001600160a01b03166340c10f1984670de0b6b3a76400006040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156145b757600080fd5b505af11580156145cb573d6000803e3d6000fd5b505050506145d7614778565b6001600160a01b03167f3a5398bda6f1f57d6c96834fa9bf02b5517bdc847d14312015a917ba421c31c9856040518082815260200191505060405180910390a250505050565b614625614778565b6000546001600160a01b03908116911614614675576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b600061469061468383611aca565b429063ffffffff615a6d16565b905080600a60008460028111156146a357fe5b60028111156146ae57fe5b8152602001908152602001600020819055507f6e57d96ae65caee513bb2adf8adff1ea16e6bb5a6154e6939c8692392c576b668282604051808360028111156146f357fe5b60ff1681526020018281526020019250505060405180910390a15050565b614719614778565b6000546001600160a01b03908116911614614769576040805162461bcd60e51b81526020600482018190526024820152600080516020615dc8833981519152604482015290519081900360640190fd5b6008805460ff19166001179055565b3390565b600d90565b6001600160a01b0383166000908152600b6020526040812054819060ff16156147ae57600091505061480f565b83600114156147d657826000815481106147c457fe5b9060005260206000200154905061480c565b826002815481106147e357fe5b90600052602060002001548402836001815481106147fd57fe5b90600052602060002001540190505b90505b9392505050565b600061480f83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250615ad3565b60008083511161489b576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b6064835111156148e4576040805162461bcd60e51b815260206004820152600f60248201526e4f7665722031303020746f6b656e7360881b604482015290519081900360640190fd5b6060835167ffffffffffffffff811180156148fe57600080fd5b50604051908082528060200260200182016040528015614928578160200160208202803683370190505b509050600080614936614778565b905060005b8651811015614bd757600087828151811061495257fe5b6020026020010151905061271081106149a5576040805162461bcd60e51b815260206004820152601060248201526f0e8ded6cadc92c840e8dede40d0d2ced60831b604482015290519081900360640190fd5b60008060008060006149b56159d1565b6001600160a01b031663088f11f3876040518263ffffffff1660e01b81526004018082815260200191505060a060405180830381600087803b1580156149fa57600080fd5b505af1158015614a0e573d6000803e3d6000fd5b505050506040513d60a0811015614a2457600080fd5b508051602082015160408301516060840151608090940151929850909650945090925090508584146001600160a01b038083163014908415908b8116908716146000614a6e6159d1565b6001600160a01b031663581781688c6040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b158015614ab357600080fd5b505af1158015614ac7573d6000803e3d6000fd5b505050506040513d6020811015614add57600080fd5b50516001600160a01b038e81169116149050898015614af95750845b8015614b025750835b8015614b0b5750825b8015614b145750815b8015614b1d5750805b15614bc057614b2a6159d1565b6001600160a01b0316638264fe988c6040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b158015614b6f57600080fd5b505af1158015614b83573d6000803e3d6000fd5b50505050614b938b61453b614cf8565b508a8f8f81518110614ba157fe5b6020908102919091010152614bbd8e600163ffffffff615a6d16565b9d505b50506001909901985061493b975050505050505050565b508115614cef5784614c6f57670de0b6b3a76400008202614bf66159b6565b6001600160a01b03166340c10f1983836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b158015614c5557600080fd5b505af1158015614c69573d6000803e3d6000fd5b50505050505b806001600160a01b03167fbc07a750767f513de2b3356e24037db0e90c9e5cdaa0d757c7e628c3d82e8f12846040518080602001828103825283818151815260200191508051906020019060200280838360005b83811015614cdb578181015183820152602001614cc3565b505050509050019250505060405180910390a25b50949350505050565b600690565b600061480f8383615b6a565b600061131582615bce565b600f90565b600080614d24614778565b90506127108410614d6f576040805162461bcd60e51b815260206004820152601060248201526f0e8ded6cadc92c840e8dede40d0d2ced60831b604482015290519081900360640190fd5b6000806000806000614d7f6159d1565b6001600160a01b031663088f11f38a6040518263ffffffff1660e01b81526004018082815260200191505060a060405180830381600087803b158015614dc457600080fd5b505af1158015614dd8573d6000803e3d6000fd5b505050506040513d60a0811015614dee57600080fd5b50805160208201516040830151606084015160809094015192985090965094509092509050888414614e54576040805162461bcd60e51b815260206004820152600a60248201526957726f6e672070756e6b60b01b604482015290519081900360640190fd5b84614e9b576040805162461bcd60e51b815260206004820152601260248201527150756e6b206e6f7420617661696c61626c6560701b604482015290519081900360640190fd5b6001600160a01b0381163014614ef0576040805162461bcd60e51b8152602060048201526015602482015274151c985b9cd9995c881b9bdd08185c1c1c9bdd9959605a1b604482015290519081900360640190fd5b8115614f38576040805162461bcd60e51b81526020600482015260126024820152714d696e2076616c7565206e6f74207a65726f60701b604482015290519081900360640190fd5b826001600160a01b0316866001600160a01b031614614f95576040805162461bcd60e51b815260206004820152601460248201527329b2b73232b91034b9903737ba1039b2b63632b960611b604482015290519081900360640190fd5b614f9d6159d1565b6001600160a01b031663581781688a6040518263ffffffff1660e01b815260040180828152602001915050602060405180830381600087803b158015614fe257600080fd5b505af1158015614ff6573d6000803e3d6000fd5b505050506040513d602081101561500c57600080fd5b50516001600160a01b03878116911614615063576040805162461bcd60e51b815260206004820152601360248201527229b2b73232b91034b9903737ba1037bbb732b960691b604482015290519081900360640190fd5b61506b6159d1565b6001600160a01b0316638264fe988a6040518263ffffffff1660e01b815260040180828152602001915050600060405180830381600087803b1580156150b057600080fd5b505af11580156150c4573d6000803e3d6000fd5b505050506150d48961453b614cf8565b508761516457670de0b6b3a76400006150eb6159b6565b6001600160a01b03166340c10f1988836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561514a57600080fd5b505af115801561515e573d6000803e3d6000fd5b50505050505b61516c614778565b6001600160a01b03167f3a5398bda6f1f57d6c96834fa9bf02b5517bdc847d14312015a917ba421c31c98a6040518082815260200191505060405180910390a250600198975050505050505050565b60006151c5614778565b9050670de0b6b3a764000082806152645750806151e06159b6565b6001600160a01b03166370a08231846040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561523557600080fd5b505afa158015615249573d6000803e3d6000fd5b505050506040513d602081101561525f57600080fd5b505110155b6152af576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b828061533f5750806152bf6159b6565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b15801561531057600080fd5b505afa158015615324573d6000803e3d6000fd5b505050506040513d602081101561533a57600080fd5b505110155b61538c576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b6000615399611439614cf8565b905060006153a6826159ec565b905060006153b682611309614cf8565b90508561543d576153c56159b6565b6001600160a01b03166379cc679086866040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561542457600080fd5b505af1158015615438573d6000803e3d6000fd5b505050505b61544981612280614cf8565b506154526159d1565b6001600160a01b0316638b72a2ec86836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156154b157600080fd5b505af11580156154c5573d6000803e3d6000fd5b50506040805184815290516001600160a01b03891693507f33631bcd0a4d34a7e2c240ab0753d5adfb7284d8ac89dab6876ec785c0cfa0e692509081900360200190a2505050505050565b600e90565b60008211615556576040805162461bcd60e51b81526020600482015260096024820152684e6f20746f6b656e7360b81b604482015290519081900360640190fd5b606482111561559e576040805162461bcd60e51b815260206004820152600f60248201526e4f7665722031303020746f6b656e7360881b604482015290519081900360640190fd5b60006155a8614778565b9050670de0b6b3a7640000830282806156495750806155c56159b6565b6001600160a01b03166370a08231846040518263ffffffff1660e01b815260040180826001600160a01b03166001600160a01b0316815260200191505060206040518083038186803b15801561561a57600080fd5b505afa15801561562e573d6000803e3d6000fd5b505050506040513d602081101561564457600080fd5b505110155b615694576040805162461bcd60e51b8152602060048201526017602482015276115490cc8c0818985b185b98d9481d1bdbc81cdb585b1b604a1b604482015290519081900360640190fd5b82806157245750806156a46159b6565b60408051636eb1769f60e11b81526001600160a01b0386811660048301523060248301529151929091169163dd62ed3e91604480820192602092909190829003018186803b1580156156f557600080fd5b505afa158015615709573d6000803e3d6000fd5b505050506040513d602081101561571f57600080fd5b505110155b615771576040805162461bcd60e51b8152602060048201526019602482015278115490cc8c08185b1b1bddd85b98d9481d1bdbc81cdb585b1b603a1b604482015290519081900360640190fd5b826157f65761577e6159b6565b6001600160a01b03166379cc679083836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b1580156157dd57600080fd5b505af11580156157f1573d6000803e3d6000fd5b505050505b60608467ffffffffffffffff8111801561580f57600080fd5b50604051908082528060200260200182016040528015615839578160200160208202803683370190505b50905060005b85811015615927576000615854611439614cf8565b90506000615861826159ec565b9050600061587182611309614cf8565b90508085858151811061588057fe5b60200260200101818152505061589881612280614cf8565b506158a16159d1565b6001600160a01b0316638b72a2ec88836040518363ffffffff1660e01b815260040180836001600160a01b03166001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561590057600080fd5b505af1158015615914573d6000803e3d6000fd5b50506001909501945061583f9350505050565b50826001600160a01b03167fbcf5ab3acba5a0c4486ea481f9aff9688ca72d992d52325968caafb9849d8b0a826040518080602001828103825283818151815260200191508051906020019060200280838360005b8381101561599457818101518382015260200161597c565b505050509050019250505060405180910390a25050505050565b620151800290565b6003546001600160a01b031690565b600061480f8383615bd2565b6004546001600160a01b031690565b600061480f8383615c98565b601354600090615a0390600163ffffffff615a6d16565b6013558142615a10614778565b60135460405160200180848152602001836001600160a01b03166001600160a01b031660601b815260140182815260200193505050506040516020818303038152906040528051906020012060001c81615a6657fe5b0692915050565b60008282018381101561480f576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600061480f8383615cb0565b60008184841115615b625760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015615b27578181015183820152602001615b0f565b50505050905090810190601f168015615b545780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b81546000908210615bac5760405162461bcd60e51b8152600401808060200182810382526022815260200180615d606022913960400191505060405180910390fd5b826000018281548110615bbb57fe5b9060005260206000200154905092915050565b5490565b60008181526001830160205260408120548015615c8e5783546000198083019190810190600090879083908110615c0557fe5b9060005260206000200154905080876000018481548110615c2257fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080615c5257fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050611315565b6000915050611315565b60009081526001919091016020526040902054151590565b6000615cbc8383615c98565b615cf257508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155611315565b506000611315565b828054828255906000526020600020908101928215615d35579160200282015b82811115615d35578251825591602001919060010190615d1a565b50615d41929150615d45565b5090565b610f6c91905b80821115615d415760008155600101615d4b56fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64735265656e7472616e637947756172643a207265656e7472616e742063616c6c004f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572bbc70db1b6c7afd11e79c0fb0051300458f1a3acb8ee9789d9b6b26c61ad9bc7a26469706673582212200acf6cddc230a4a23f767dfde065f59e4ec5f5d753a3a36b75124fd7782860a264736f6c63430006080033
[ 10, 5, 11 ]
0x5b08999b131ef09a83f3eb7e2d2efcef37b4851a
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); 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) external view returns (uint256); } interface ProtocolAdapter { /** * @dev MUST return "Asset" or "Debt". * SHOULD be implemented by the public constant state variable. */ function adapterType() external pure returns (string memory); /** * @dev MUST return token type (default is "ERC20"). * SHOULD be implemented by the public constant state variable. */ function tokenType() external pure returns (string memory); /** * @dev MUST return amount of the given token locked on the protocol by the given account. */ function getBalance(address token, address account) external view returns (uint256); } interface TokenGeyser { function totalStakedFor(address) external view returns (uint256); } contract AmpleforthAdapter is ProtocolAdapter { string public constant override adapterType = "Asset"; string public constant override tokenType = "ERC20"; address internal constant AMPL = 0xD46bA6D942050d489DBd938a2C909A5d5039A161; address internal constant UNI_AMPL_WETH = 0xc5be99A02C6857f9Eac67BbCE58DF5572498F40c; address internal constant GEYSER_PILOT = 0xD36132E0c1141B26E62733e018f12Eb38A7b7678; address internal constant GEYSER_BEEHIVE_V1 = 0x0eEf70ab0638A763acb5178Dd3C62E49767fd940; address internal constant GEYSER_BEEHIVE_V2 = 0x23796Bc856ed786dCC505984fd538f91dAD3194A; /** * @return AMPL balance or amount of UNI-tokens locked on the protocol by the given account. * @dev Implementation of ProtocolAdapter interface function. */ function getBalance(address token, address account) external view override returns (uint256) { if (token == AMPL) { return ERC20(AMPL).balanceOf(account); } else if (token == UNI_AMPL_WETH) { uint totalStaked = 0; totalStaked += TokenGeyser(GEYSER_PILOT).totalStakedFor(account); totalStaked += TokenGeyser(GEYSER_BEEHIVE_V1).totalStakedFor(account); totalStaked += TokenGeyser(GEYSER_BEEHIVE_V2).totalStakedFor(account); return totalStaked; } else { return 0; } } }
0x608060405234801561001057600080fd5b50600436106100415760003560e01c806330fa738c14610046578063d4fac45d14610064578063f72c079114610084575b600080fd5b61004e61008c565b60405161005b9190610497565b60405180910390f35b61007761007236600461042a565b6100c5565b60405161005b9190610508565b61004e6103cd565b6040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081565b600073ffffffffffffffffffffffffffffffffffffffff831673d46ba6d942050d489dbd938a2c909a5d5039a16114156101a0576040517f70a0823100000000000000000000000000000000000000000000000000000000815273d46ba6d942050d489dbd938a2c909a5d5039a161906370a0823190610149908590600401610476565b60206040518083038186803b15801561016157600080fd5b505afa158015610175573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610199919061045e565b90506103c7565b73ffffffffffffffffffffffffffffffffffffffff831673c5be99a02c6857f9eac67bbce58df5572498f40c14156103c3576040517f4b341aed00000000000000000000000000000000000000000000000000000000815260009073d36132e0c1141b26e62733e018f12eb38a7b767890634b341aed90610225908690600401610476565b60206040518083038186803b15801561023d57600080fd5b505afa158015610251573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610275919061045e565b6040517f4b341aed000000000000000000000000000000000000000000000000000000008152910190730eef70ab0638a763acb5178dd3c62e49767fd94090634b341aed906102c8908690600401610476565b60206040518083038186803b1580156102e057600080fd5b505afa1580156102f4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610318919061045e565b6040517f4b341aed0000000000000000000000000000000000000000000000000000000081529101907323796bc856ed786dcc505984fd538f91dad3194a90634b341aed9061036b908690600401610476565b60206040518083038186803b15801561038357600080fd5b505afa158015610397573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103bb919061045e565b0190506103c7565b5060005b92915050565b6040518060400160405280600581526020017f417373657400000000000000000000000000000000000000000000000000000081525081565b803573ffffffffffffffffffffffffffffffffffffffff811681146103c757600080fd5b6000806040838503121561043c578182fd5b6104468484610406565b91506104558460208501610406565b90509250929050565b60006020828403121561046f578081fd5b5051919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080835283518082850152825b818110156104c3578581018301518582016040015282016104a7565b818111156104d45783604083870101525b50601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016929092016040019392505050565b9081526020019056fea2646970667358221220d23521f60e6d904cece0a6f7f7aed712475d62c7e2d6ce92efbe6fa10ec750b864736f6c63430006050033
[ 38 ]
0x5c38d75aa0f06d851a4deb2e40b0fcc92554fa75
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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"); } } library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } contract Decryption { function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } 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)); } } library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - (subtracted.a), p); } else { difference.a = p - (addmod(subtracted.a, p - (diminished.a), p)); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - (subtracted.b), p); } else { difference.b = p - (addmod(subtracted.b, p - (diminished.b), p)); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = p - addmod(t2, p - t0, p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = p - mulmod(value.b, t3, p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG1() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = p - sum.y.a; sum.y.b = p - sum.y.b; } function toUS(G2Point memory value) internal pure returns (G2Point memory) { return G2Point({ x: value.x.mulFp2(Fp2Operations.Fp2Point({ a: 1, b: 0 }).squaredFp2()), y: value.y.mulFp2( Fp2Operations.Fp2Point({ a: 1, b: 0 }).mulFp2(Fp2Operations.Fp2Point({ a: 1, b: 0 }).squaredFp2()) ) }); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = p - result.y.a; result.y.b = p - result.y.b; } } function mulG2( G2Point memory value, uint scalar ) internal view returns (G2Point memory result) { uint step = scalar; result = G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); G2Point memory tmp = value; uint gs = gasleft(); while (step > 0) { if (step % 2 == 1) { result = addG2(result, tmp); } gs = gasleft(); tmp = doubleG2(tmp); step >>= 1; } } } library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } interface ILocker { /** * @dev Returns the locked amount of untransferable tokens of a given `wallet` */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns the locked amount of untransferable and un-delegatable tokens of a given `wallet`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } interface ISkaleDKG { function openChannel(bytes32 schainId) external; function deleteChannel(bytes32 schainId) external; function isLastDKGSuccesful(bytes32 groupIndex) external view returns (bool); function isChannelOpened(bytes32 schainId) external view returns (bool); } 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; } library MathUtils { event UnderflowError( uint a, uint b ); uint constant private _EPS = 1e6; function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Can't reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint newValue = sequence.value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value != newValue) { sequence.value = newValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint _i = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len.sub(1); while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * Adds actual contract to mapping of actual contract addresses * @param contractsName - contracts name in skale manager system * @param newContractsAddress - contracts address in skale manager system */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract * @param contractName - human readable name of contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName3))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } contract Punisher is Permissions, ILocker { /** * @dev Emitted when a slashing condition occurs. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted when a forgive condition occurs. */ event Forgive( address wallet, uint amount ); // holder => tokens mapping (address => uint) private _locked; /** * @dev Executes slashing on a validator and its delegations by an `amount` * of tokens. Currently, SkaleDKG is the only service allowed to execute * slashing. * * Emits a Slash event. * * @param validatorId uint validator to be slashed * @param amount uint slashed amount */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Owner to forgive a slashing condition. * * Emits a Forgive event. * * @param holder address of the slashed * @param amount uint amount to be forgiven */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See ILocker-getAndUpdateLockedAmount */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker-getAndUpdateForbiddenForDelegationAmount */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } // informs that Schain is created event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); event SchainDeleted( address owner, string name, bytes32 indexed schainId ); event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); event NodeAdded( bytes32 schainId, uint newNode ); // informs that Schain based on some Nodes event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param data - Schain's data */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schian"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev deleteSchain - removes Schain from the system * function could be run only by executor * @param from - owner of Schain * @param name - Schain name */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not an owner of Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccesful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No any free Nodes for rotation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev verifySignature - verify signature which create Group by Groups BLS master public key * @param signatureA - first part of BLS signature * @param signatureB - second part of BLS signature * @param hash - hashed message * @param counter - smallest sub from square * @param hashA - first part of hashed message * @param hashB - second part of hashed message * @param schainName - name of the Schain * @return true - if correct, false - if not */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev getSchainPrice - returns current price for given Schain * @param typeOfSchain - type of Schain * @param lifetime - lifetime of Schain * @return current price for given Schain */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev getNodesDataFromTypeOfSchain - returns number if Nodes * and part of Node which needed to this Schain * @param typeOfSchain - type of Schain * @return numberOfNodes - number of Nodes needed to this Schain * @return partOfNode - divisor of given type of Schain */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { revert("Bad schain type"); } } function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev fallbackSchainParameterDataConverter - converts data from bytes to normal parameters * @param data - concatenated parameters * @return schainParameters Parsed lifetime, typeOfSchain, nonce and name */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev _createGroupForSchain - creates Group for Schain * @param schainName - name of Schain * @param schainId - hash by name of Schain * @param numberOfNodes - number of Nodes needed for this Schain * @param partOfNode - divisor of given type of Schain */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev _addSchain - create Schain in the system * function could be run only by executor * @param from - owner of Schain * @param deposit - received amoung of SKL * @param schainParameters - Schain's data */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; /** * @dev initializeSchain - initializes Schain * function could be run only by executor * @param name - SChain name * @param from - Schain owner * @param lifetime - initial lifetime of Schain * @param deposit - given amount of SKL */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev setSchainIndex - adds Schain's hash to owner * function could be run only by executor * @param schainId - hash by Schain name * @param from - Schain owner */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev changeLifetime - changes Lifetime for Schain * function could be run only by executor * @param schainId - hash by Schain name * @param lifetime - time which would be added to lifetime of Schain * @param deposit - amount of SKL which payed for this time */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev removeSchain - removes Schain from the system * function could be run only by executor * @param schainId - hash by Schain name * @param from - owner of Schain */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainId = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainId); } function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev deleteGroup - delete Group from Data contract * function could be run only by executor * @param schainId - Groups identifier */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; if (skaleDKG.isChannelOpened(schainId)) { skaleDKG.deleteChannel(schainId); } } /** * @dev setException - sets a Node like exception * function could be run only by executor * @param schainId - Groups identifier * @param nodeIndex - index of Node which would be notes like exception */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev setNodeInGroup - adds Node to Group * function could be run only by executor * @param schainId - Groups * @param nodeIndex - index of Node which would be added to the Group */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev getSchains - gets all Schains at the system * @return array of hashes by Schain names */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev getSchainsPartOfNode - gets occupied space for given Schain * @param schainId - hash by Schain name * @return occupied space */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev getSchainListSize - gets number of created Schains at the system by owner * @param from - owner of Schain * return number of Schains */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev getSchainIdsByAddress - gets array of hashes by Schain names which owned by `from` * @param from - owner of some Schains * @return array of hashes by Schain names */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev getSchainIdsForNode - returns array of hashes by Schain names, * which given Node composed * @param nodeIndex - index of Node * @return array of hashes by Schain names */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev isSchainNameAvailable - checks is given name available * Need to delete - copy of web3.utils.soliditySha3 * @param name - possible new name of Schain * @return if available - true, else - false */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId]; } /** * @dev isTimeExpired - checks is Schain lifetime expired * @param schainId - hash by Schain name * @return if expired - true, else - false */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev isOwnerAddress - checks is `from` - owner of `schainId` Schain * @param from - owner of Schain * @param schainId - hash by Schain name * @return if owner - true, else - false */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev getNumberOfNodesInGroup - shows number of Nodes in Group * @param schainId - Groups identifier * @return number of Nodes in Group */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev getNodesInGroup - shows Nodes in Group * @param schainId - Groups identifier * @return array of indexes of Nodes in Group */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev getNodeIndexInGroup - looks for Node in Group * @param schainId - Groups identifier * @param nodeId - Nodes identifier * @return index of Node in Group */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; } /** * @dev addSchainForNode - adds Schain hash to Node * function could be run only by executor * @param nodeIndex - index of Node * @param schainId - hash by Schain name */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); } else { schainsForNodes[nodeIndex][holesForNodes[nodeIndex][0]] = schainId; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForNodes[nodeIndex].length; i++) { if (min > holesForNodes[nodeIndex][i]) { min = holesForNodes[nodeIndex][i]; index = i; } } if (min == uint(-1)) { delete holesForNodes[nodeIndex]; } else { holesForNodes[nodeIndex][0] = min; holesForNodes[nodeIndex][index] = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; holesForNodes[nodeIndex].pop(); } } } /** * @dev removesSchainForNode - clean given Node of Schain * function could be run only by executor * @param nodeIndex - index of Node * @param schainIndex - index of Schain in schainsForNodes array by this Node */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev getLengthOfSchainsForNode - returns number of Schains which contain given Node * @param nodeIndex - index of Node * @return number of Schains */ function getLengthOfSchainsForNode(uint nodeIndex) public view returns (uint) { return schainsForNodes[nodeIndex].length; } /** * @dev findSchainAtSchainsForNode - finds index of Schain at schainsForNode array * @param nodeIndex - index of Node at common array of Nodes * @param schainId - hash of name of Schain * @return index of Schain at schainsForNode array */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { uint length = getLengthOfSchainsForNode(nodeIndex); for (uint i = 0; i < length; i++) { if (schainsForNodes[nodeIndex][i] == schainId) { return i; } } return length; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev _generateGroup - generates Group for Schain * @param schainId - index of Group */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev findNode - find local index of Node in Schain * @param schainId - Groups identifier * @param nodeIndex - global index of Node * @return local index of Node in Schain */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); event BountyGot( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce}); nodes.createNode(msg.sender, params); // uint nodeIndex = nodes.createNode(msg.sender, params); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.addMonitor(nodeIndex); } function nodeExit(uint nodeIndex) external { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } bool completed; bool isSchains = false; if (schainsInternal.getActiveSchain(nodeIndex) != bytes32(0)) { completed = nodeRotation.exitFromSchain(nodeIndex); isSchains = true; } else { completed = true; } if (completed) { require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime(nodeIndex, now.add(isSchains ? constants.rotationDelay() : 0)); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.removeCheckedNodes(nodeIndex); // monitors.deleteMonitor(nodeIndex); nodes.deleteNodeForValidator(validatorId, nodeIndex); } } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } // function sendVerdict(uint fromMonitorIndex, Monitors.Verdict calldata verdict) external { // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // require(nodes.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // // additional checks for monitoring inside sendVerdict // monitors.sendVerdict(fromMonitorIndex, verdict); // } // function sendVerdicts(uint fromMonitorIndex, Monitors.Verdict[] calldata verdicts) external { // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // require(nodes.isNodeExist(msg.sender, fromMonitorIndex), "Node does not exist for Message sender"); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // for (uint i = 0; i < verdicts.length; i++) { // // additional checks for monitoring inside sendVerdict // monitors.sendVerdict(fromMonitorIndex, verdicts[i]); // } // } function getBounty(uint nodeIndex) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require( nodes.isNodeActive(nodeIndex) || nodes.isNodeLeaving(nodeIndex), "Node is not Active and is not Leaving" ); Bounty bountyContract = Bounty(contractManager.getContract("Bounty")); uint averageDowntime; uint averageLatency; Monitors monitors = Monitors(contractManager.getContract("Monitors")); (averageDowntime, averageLatency) = monitors.calculateMetrics(nodeIndex); uint bounty = bountyContract.getBounty( nodeIndex, averageDowntime, averageLatency); nodes.changeNodeLastRewardDate(nodeIndex); // monitors.deleteMonitor(nodeIndex); // monitors.addMonitor(nodeIndex); if (bounty > 0) { _payBounty(bounty, nodes.getValidatorId(nodeIndex)); } _emitBountyEvent(nodeIndex, msg.sender, averageDowntime, averageLatency, bounty); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _emitBountyEvent( uint nodeIndex, address from, uint averageDowntime, uint averageLatency, uint bounty ) private { Monitors monitors = Monitors(contractManager.getContract("Monitors")); uint previousBlockEvent = monitors.getLastBountyBlock(nodeIndex); monitors.setLastBountyBlock(nodeIndex); emit BountyGot( nodeIndex, from, averageDowntime, averageLatency, bounty, previousBlockEvent, block.timestamp, gasleft()); } } contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB; if (!(signature.a == 0 && signature.b == 0)) { newSignB = Fp2Operations.P.sub((signature.b % Fp2Operations.P)); } else { newSignB = signature.b; } require(G2Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G2Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUserCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Can't add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUserCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } function _totalDelegatedSatisfiesProofOfUserCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } contract TokenState is Permissions, ILocker { /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); string[] private _lockers; /** * @dev Return and update the total locked amount of a given `holder`. * * @param holder address of the token holder * @return total locked amount */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint locked = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } /** * @dev Return and update the total locked and un-delegatable amount of a given `holder`. * * @param holder address of the token holder * @return amount total slashed amount (non-transferable and non-delegatable) */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a LockerWasRemoved event. * * @param locker string name of contract to remove from locker */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a LockerWasAdded event. * * @param locker string name of contract to add to locker */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); event ValidatorWasEnabled( uint validatorId ); event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator Id. * * Requirements: * * - sender must not already have registered a validator Id. * - fee rate must be between 0 - 1000‰. Note: per mille! * * Emits ValidatorRegistered event. * * @param name string * @param description string * @param feeRate uint Fee charged on delegations by the validator per mille * @param minimumDelegationAmount uint Minimum delegation amount accepted by the validator */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate < 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the validator whitelist. Once turned off the * whitelist cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows a validator to request a new address. * * Requirements: * * - new address must not be null * - new address must not be already registered as a validator * * @param newValidatorAddress address */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a given node address. * * Requirements: * * - the given signature must be valid. * - the address must not be assigned to a validator. * * Emits NodeAddressWasAdded event. * * @param nodeAddress address * @param sig bytes signature of validator Id by node operator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a given node address from a validator. * * Emits NodeAddressWasRemoved event. * * @param nodeAddress address */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); _removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. * * @param newName string */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. * * @param newDescription string */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - validator must not have already enabled accepting new requests */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - validator must not have already stopped accepting new requests */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } /** * @dev Returns the amount of validator bond. * * @param validatorId uint ID of validator to return the amount of locked funds * @return bondAmount uint the amount of self-delegated funds by the validator */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns a list of trusted validators. * * @return uint[] trusted validators */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } function checkMinimumDelegation(uint validatorId, uint amount) external view checkValidatorExists(validatorId) allow("DelegationController") returns (bool) { return validators[validatorId].minimumDelegationAmount <= amount ? true : false; } function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function isAuthorizedValidator(uint validatorId) external view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator with given address does not exist"); } function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } // private function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _removeNodeAddress(uint validatorId, address nodeAddress) private { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } contract Bounty is Permissions { uint public constant STAGE_LENGTH = 31558150; // 1 year uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant BOUNTY = 96250000 * 1e18; uint private _nextStage; uint private _stagePool; bool public bountyReduction; uint private _nodesPerRewardPeriod; uint private _nodesRemainingPerRewardPeriod; uint private _rewardPeriodFinished; function getBounty( uint nodeIndex, uint downtime, uint latency ) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); _refillStagePool(constantsHolder); if (_rewardPeriodFinished <= now) { _updateNodesPerRewardPeriod(constantsHolder, nodes); } uint bounty = _calculateMaximumBountyAmount(_stagePool, _nextStage, nodeIndex, constantsHolder, nodes); bounty = _reduceBounty( bounty, nodeIndex, downtime, latency, nodes, constantsHolder ); _stagePool = _stagePool.sub(bounty); _nodesRemainingPerRewardPeriod = _nodesRemainingPerRewardPeriod.sub(1); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function calculateNormalBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint stagePoolSize; uint nextStage; (stagePoolSize, nextStage) = _getStagePoolSize(constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, nextStage, nodeIndex, constantsHolder, nodes ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextStage = 0; _stagePool = 0; _rewardPeriodFinished = 0; bountyReduction = false; } // private function _calculateMaximumBountyAmount( uint stagePoolSize, uint nextStage, uint nodeIndex, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } uint numberOfRewards = _getStageBeginningTimestamp(nextStage, constantsHolder) .sub(now) .div(constantsHolder.rewardPeriod()); uint numberOfRewardsPerAllNodes = numberOfRewards.mul(_nodesPerRewardPeriod); return stagePoolSize.div( numberOfRewardsPerAllNodes.add(_nodesRemainingPerRewardPeriod) ); } function _getStageBeginningTimestamp(uint stage, ConstantsHolder constantsHolder) private view returns (uint) { return constantsHolder.launchTimestamp().add(stage.mul(STAGE_LENGTH)); } function _getStagePoolSize(ConstantsHolder constantsHolder) private view returns (uint stagePool, uint nextStage) { stagePool = _stagePool; for (nextStage = _nextStage; now >= _getStageBeginningTimestamp(nextStage, constantsHolder); ++nextStage) { stagePool += _getStageReward(_nextStage); } } function _refillStagePool(ConstantsHolder constantsHolder) private { (_stagePool, _nextStage) = _getStagePoolSize(constantsHolder); } function _updateNodesPerRewardPeriod(ConstantsHolder constantsHolder, Nodes nodes) private { _nodesPerRewardPeriod = nodes.getNumberOnlineNodes(); _nodesRemainingPerRewardPeriod = _nodesPerRewardPeriod; _rewardPeriodFinished = now.add(uint(constantsHolder.rewardPeriod())); } function _getStageReward(uint stage) private pure returns (uint) { if (stage >= 6) { return BOUNTY.div(2 ** stage.sub(6).div(3)); } else { if (stage == 0) { return YEAR1_BOUNTY; } else if (stage == 1) { return YEAR2_BOUNTY; } else if (stage == 2) { return YEAR3_BOUNTY; } else if (stage == 3) { return YEAR4_BOUNTY; } else if (stage == 4) { return YEAR5_BOUNTY; } else { return YEAR6_BOUNTY; } } } function _reduceBounty( uint bounty, uint nodeIndex, uint downtime, uint latency, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = _reduceBountyByDowntime(bounty, nodeIndex, downtime, nodes, constants); if (latency > constants.allowableLatency()) { // reduce bounty because latency is too big reducedBounty = reducedBounty.mul(constants.allowableLatency()).div(latency); } if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _reduceBountyByDowntime( uint bounty, uint nodeIndex, uint downtime, Nodes nodes, ConstantsHolder constants ) private view returns (uint reducedBounty) { reducedBounty = bounty; uint getBountyDeadline = uint(nodes.getNodeLastRewardDate(nodeIndex)) .add(constants.rewardPeriod()) .add(constants.deltaPeriod()); uint numberOfExpiredIntervals; if (now > getBountyDeadline) { numberOfExpiredIntervals = now.sub(getBountyDeadline).div(constants.checkTime()); } else { numberOfExpiredIntervals = 0; } uint normalDowntime = uint(constants.rewardPeriod()) .sub(constants.deltaPeriod()) .div(constants.checkTime()) .div(constants.DOWNTIME_THRESHOLD_PART()); uint totalDowntime = downtime.add(numberOfExpiredIntervals); if (totalDowntime > normalDowntime) { // reduce bounty because downtime is too big uint penalty = bounty .mul(totalDowntime) .div( uint(constants.rewardPeriod()).sub(constants.deltaPeriod()) .div(constants.checkTime()) ); if (bounty > penalty) { reducedBounty = bounty.sub(penalty); } else { reducedBounty = 0; } } } } contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/8 of Node) uint8 public constant MEDIUM_DIVISOR = 8; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; /** * Set reward and delta periods to new one, run only by owner. This function * only for tests. * @param newRewardPeriod - new Reward period * @param newDeltaPeriod - new Delta period */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * Set new check time. This function only for tests. * @param newCheckTime - new check time */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * Set latency new one in ms, run only by owner. This function * only for tests. * @param newAllowableLatency - new Allowable Latency */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Can't set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; } } contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * @param validatorId uint ID of validator to receive delegation proposal * @param amount uint amount of proposed delegation * @param delegationPeriod uint period of proposed delegation * @param info string extra information provided by the token holder (if any) */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); TokenState tokenState = TokenState(contractManager.getContract("TokenState")); require( validatorService.checkMinimumDelegation(validatorId, amount), "Amount does not meet the validator's minimum delegation amount"); require( validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require( delegationPeriodManager.isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); require( validatorService.isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = skaleToken.balanceOf(msg.sender); uint forbiddenForDelegation = tokenState.getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See ILocker. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows a token holder to cancel a delegation proposal. * * Requirements: * * - the sender must be the token holder of the delegation proposal. * - the delegation must still be in a PROPOSED state. * * Emits a DelegationRequestCanceledByUser event. * * @param delegationId uint ID of delegation proposal */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a DelegationAccepted event. * * @param delegationId uint ID of delegation proposal */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( validatorService.checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); tokenLaunchLocker.handleDelegationAdd( delegations[delegationId].holder, delegationId, delegations[delegationId].amount, delegations[delegationId].started); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } /** * @dev Allows a delegator to undelegate a specific delegation. * * Requirements: * * - the sender must be the delegator. * - the delegation must be in DELEGATED state. * * Emits an UndelegationRequested event. * * @param delegationId uint ID of delegation to undelegate */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); tokenLaunchLocker.handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); emit UndelegationRequested(delegationId); } /** * @dev Allows the Punisher to confiscate an `amount` of stake from * `validatorId` by slashing. This slashes all delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manger to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * See Punisher. * * Emits a SlashingEvent. * * @param validatorId uint validator to slash * @param amount uint amount to slash * */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); } function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allow("Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function getAndUpdateDelegatedToValidator(uint validatorId, uint month) public allow("Nodes") returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. * * @param delegationId uint ID of the delegation */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); if (_getCurrentMonth() == timeHelpers.timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); require( _lockedInPendingDelegations[holder].month == currentMonth, "There are no delegation requests this month"); require(_lockedInPendingDelegations[holder].amount >= amount, "Unlocking amount is too big"); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); return timeHelpers.getCurrentMonth(); } function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getContract("Punisher")); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < constantsHolder.limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } } contract DelegationPeriodManager is Permissions { /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); mapping (uint => uint) public stakeMultipliers; /** * @dev Creates a new available delegation period and return in the network. * Only the owner may set new delegation period and returns in the network. * * Emits a DelegationPeriodWasSet event. * * @param monthsCount uint delegation duration in months * @param stakeMultiplier uint return for delegation */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. * * @param monthsCount uint delegation duration in months * @return bool True if delegation period is allowed */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0 ? true : false; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[3] = 100; // 3 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when a bounty is withdrawn by the token holder. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn by the validator. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when a bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 groupIndex) external allow("SkaleDKG") { _previousSchainsPublicKeys[groupIndex].push(_schainsPublicKeys[groupIndex]); delete _schainsPublicKeys[groupIndex]; } function initPublicKeyInProgress(bytes32 groupIndex) external allow("SkaleDKG") { _publicKeysInProgress[groupIndex] = G2Operations.getG2Zero(); } function adding(bytes32 groupIndex, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[groupIndex] = value.addG2(_publicKeysInProgress[groupIndex]); } function finalizePublicKey(bytes32 groupIndex) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(groupIndex)) { _previousSchainsPublicKeys[groupIndex].push(_schainsPublicKeys[groupIndex]); } _schainsPublicKeys[groupIndex] = _publicKeysInProgress[groupIndex]; delete _publicKeysInProgress[groupIndex]; } function getCommonPublicKey(bytes32 groupIndex) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[groupIndex]; } function getPreviousPublicKey(bytes32 groupIndex) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[groupIndex].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[groupIndex][length - 1]; } function getAllPreviousPublicKeys(bytes32 groupIndex) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[groupIndex]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } contract Monitors is Permissions { using StringUtils for string; using SafeCast for uint; struct Verdict { uint toNodeIndex; uint32 downtime; uint32 latency; } struct CheckedNode { uint nodeIndex; uint time; } struct CheckedNodeWithIp { uint nodeIndex; uint time; bytes4 ip; } mapping (bytes32 => CheckedNode[]) public checkedNodes; mapping (bytes32 => uint[][]) public verdicts; mapping (bytes32 => uint[]) public groupsForMonitors; mapping (bytes32 => uint) public lastVerdictBlocks; mapping (bytes32 => uint) public lastBountyBlocks; event MonitorCreated( uint nodeIndex, bytes32 monitorIndex, uint numberOfMonitors, uint[] nodesInGroup, uint time, uint gasSpend ); event VerdictWasSent( uint indexed fromMonitorIndex, uint indexed toNodeIndex, uint32 downtime, uint32 latency, bool status, uint previousBlockEvent, uint time, uint gasSpend ); event MetricsWereCalculated( uint forNodeIndex, uint32 averageDowntime, uint32 averageLatency, uint time, uint gasSpend ); event PeriodsWereSet( uint rewardPeriod, uint deltaPeriod, uint time, uint gasSpend ); event MonitorRotated( bytes32 monitorIndex, uint newNode ); /** * addMonitor - setup monitors of node */ function addMonitor(uint nodeIndex) external allow("SkaleManager") { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); _generateGroup(monitorIndex, nodeIndex, constantsHolder.NUMBER_OF_MONITORS()); CheckedNode memory checkedNode = _getCheckedNodeData(nodeIndex); for (uint i = 0; i < groupsForMonitors[monitorIndex].length; i++) { bytes32 index = keccak256(abi.encodePacked(groupsForMonitors[monitorIndex][i])); addCheckedNode(index, checkedNode); } emit MonitorCreated( nodeIndex, monitorIndex, groupsForMonitors[monitorIndex].length, groupsForMonitors[monitorIndex], block.timestamp, gasleft() ); } function deleteMonitor(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); while (verdicts[keccak256(abi.encodePacked(nodeIndex))].length > 0) { verdicts[keccak256(abi.encodePacked(nodeIndex))].pop(); } uint[] memory nodesInGroup = groupsForMonitors[monitorIndex]; uint index; bytes32 monitoringIndex; for (uint i = 0; i < nodesInGroup.length; i++) { monitoringIndex = keccak256(abi.encodePacked(nodesInGroup[i])); (index, ) = _find(monitoringIndex, nodeIndex); if (index < checkedNodes[monitoringIndex].length) { if (index != checkedNodes[monitoringIndex].length.sub(1)) { checkedNodes[monitoringIndex][index] = checkedNodes[monitoringIndex][checkedNodes[monitoringIndex].length.sub(1)]; } checkedNodes[monitoringIndex].pop(); } } delete groupsForMonitors[monitorIndex]; } function removeCheckedNodes(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); delete checkedNodes[monitorIndex]; } function sendVerdict(uint fromMonitorIndex, Verdict calldata verdict) external allow("SkaleManager") { uint index; uint time; bytes32 monitorIndex = keccak256(abi.encodePacked(fromMonitorIndex)); (index, time) = _find(monitorIndex, verdict.toNodeIndex); require(time > 0, "Checked Node does not exist in MonitorsArray"); if (time <= block.timestamp) { if (index != checkedNodes[monitorIndex].length.sub(1)) { checkedNodes[monitorIndex][index] = checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; } delete checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; checkedNodes[monitorIndex].pop(); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bool receiveVerdict = time.add(constantsHolder.deltaPeriod()) > block.timestamp; if (receiveVerdict) { verdicts[keccak256(abi.encodePacked(verdict.toNodeIndex))].push( [uint(verdict.downtime), uint(verdict.latency)] ); } _emitVerdictsEvent(fromMonitorIndex, verdict, receiveVerdict); } } function calculateMetrics(uint nodeIndex) external allow("SkaleManager") returns (uint averageDowntime, uint averageLatency) { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); uint lengthOfArray = getLengthOfMetrics(monitorIndex); uint[] memory downtimeArray = new uint[](lengthOfArray); uint[] memory latencyArray = new uint[](lengthOfArray); for (uint i = 0; i < lengthOfArray; i++) { downtimeArray[i] = verdicts[monitorIndex][i][0]; latencyArray[i] = verdicts[monitorIndex][i][1]; } if (lengthOfArray > 0) { averageDowntime = _median(downtimeArray); averageLatency = _median(latencyArray); } delete verdicts[monitorIndex]; } function setLastBountyBlock(uint nodeIndex) external allow("SkaleManager") { lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))] = block.number; } function getCheckedArray(bytes32 monitorIndex) external view returns (CheckedNodeWithIp[] memory checkedNodesWithIp) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNodesWithIp = new CheckedNodeWithIp[](checkedNodes[monitorIndex].length); for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { checkedNodesWithIp[i].nodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodesWithIp[i].time = checkedNodes[monitorIndex][i].time; checkedNodesWithIp[i].ip = nodes.getNodeIP(checkedNodes[monitorIndex][i].nodeIndex); } } function getLastBountyBlock(uint nodeIndex) external view returns (uint) { return lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))]; } function getNodesInGroup(bytes32 monitorIndex) external view returns (uint[] memory) { return groupsForMonitors[monitorIndex]; } function getNumberOfNodesInGroup(bytes32 monitorIndex) external view returns (uint) { return groupsForMonitors[monitorIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * Add checked node or update existing one if it is already exits */ function addCheckedNode(bytes32 monitorIndex, CheckedNode memory checkedNode) public allow("SkaleManager") { for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { if (checkedNodes[monitorIndex][i].nodeIndex == checkedNode.nodeIndex) { checkedNodes[monitorIndex][i] = checkedNode; return; } } checkedNodes[monitorIndex].push(checkedNode); } function getLastReceivedVerdictBlock(uint nodeIndex) public view returns (uint) { return lastVerdictBlocks[keccak256(abi.encodePacked(nodeIndex))]; } function getLengthOfMetrics(bytes32 monitorIndex) public view returns (uint) { return verdicts[monitorIndex].length; } function _generateGroup(bytes32 monitorIndex, uint nodeIndex, uint numberOfNodes) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint[] memory activeNodes = nodes.getActiveNodeIds(); uint numberOfNodesInGroup; uint availableAmount = activeNodes.length.sub((nodes.isNodeActive(nodeIndex)) ? 1 : 0); if (numberOfNodes > availableAmount) { numberOfNodesInGroup = availableAmount; } else { numberOfNodesInGroup = numberOfNodes; } uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), monitorIndex))); for (uint i = 0; i < numberOfNodesInGroup; ++i) { uint index = random % (activeNodes.length.sub(ignoringTail)); if (activeNodes[index] == nodeIndex) { _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; index = random % (activeNodes.length.sub(ignoringTail)); } groupsForMonitors[monitorIndex].push(activeNodes[index]); _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; } } function _median(uint[] memory values) private pure returns (uint) { if (values.length < 1) { revert("Can't calculate _median of empty array"); } _quickSort(values, 0, values.length.sub(1)); return values[values.length.div(2)]; } function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } function _find(bytes32 monitorIndex, uint nodeIndex) private view returns (uint index, uint time) { index = checkedNodes[monitorIndex].length; time = 0; for (uint i = 0; i < checkedNodes[monitorIndex].length; i++) { uint checkedNodeNodeIndex; uint checkedNodeTime; checkedNodeNodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodeTime = checkedNodes[monitorIndex][i].time; if (checkedNodeNodeIndex == nodeIndex && (time == 0 || checkedNodeTime < time)) { index = i; time = checkedNodeTime; } } } function _quickSort(uint[] memory array, uint left, uint right) private pure { uint leftIndex = left; uint rightIndex = right; uint middle = array[right.add(left).div(2)]; while (leftIndex <= rightIndex) { while (array[leftIndex] < middle) { leftIndex++; } while (middle < array[rightIndex]) { rightIndex--; } if (leftIndex <= rightIndex) { (array[leftIndex], array[rightIndex]) = (array[rightIndex], array[leftIndex]); leftIndex++; rightIndex = (rightIndex > 0 ? rightIndex.sub(1) : 0); } } if (left < rightIndex) _quickSort(array, left, rightIndex); if (leftIndex < right) _quickSort(array, leftIndex, right); } function _getCheckedNodeData(uint nodeIndex) private view returns (CheckedNode memory checkedNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNode.nodeIndex = nodeIndex; checkedNode.time = nodes.getNodeNextRewardDate(nodeIndex).sub(constantsHolder.deltaPeriod()); } function _emitVerdictsEvent( uint fromMonitorIndex, Verdict memory verdict, bool receiveVerdict ) private { uint previousBlockEvent = getLastReceivedVerdictBlock(verdict.toNodeIndex); lastVerdictBlocks[keccak256(abi.encodePacked(verdict.toNodeIndex))] = block.number; emit VerdictWasSent( fromMonitorIndex, verdict.toNodeIndex, verdict.downtime, verdict.latency, receiveVerdict, previousBlockEvent, block.timestamp, gasleft() ); } } contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; /** * nodeIndex - index of Node which is in process of rotation(left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No any free Nodes for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str()); string memory dkgRevert = "DKG proccess did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccesful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev selectNodeToGroup - pseudo-randomly select new Node for Schain * @param schainId - hash of name of Schain * @return nodeIndex - global index of Node */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No any free Nodes for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; // informs that Node is created event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint time, uint gasSpend ); // informs that node is fully finished quitting from the system event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); // informs that owner starts the procedure of quitting the Node from the system event ExitInited( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } /** * @dev removeSpaceFromFractionalNode - occupies space from Fractional Node * function could be run only by Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be occupied */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev adSpaceToFractionalNode - returns space to Fractional Node * function could be run only be Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be returned */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev changeNodeLastRewardDate - changes Node's last reward date * function could be run only by SkaleManager * @param nodeIndex - index of Node */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev createNode - creates new Node and add it to the Nodes contract * function could be only run by SkaleManager * @param from - owner of Node */ // * @return nodeIndex - index of Node function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name has already registered"); require(params.port > 0, "Port is zero"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, block.timestamp, gasleft()); } /** * @dev initExit - initiate a procedure of quitting the system * function could be only run by SkaleManager * @param nodeIndex - index of Node * @return true - if everything OK */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { _setNodeLeaving(nodeIndex); emit ExitInited( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev completeExit - finish a procedure of quitting the system * function could be run only by SkaleManager * @param nodeIndex - index of Node * @return amount of SKL which be returned */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); } function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function setNodeInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.In_Maintenance; } function removeNodeFromInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintence"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.Active; } function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev isTimeForReward - checks if time for reward has come * @param nodeIndex - index of Node * @return if time for reward has come - true, else - false */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return uint(nodes[nodeIndex].lastRewardDate).add(constantsHolder.rewardPeriod()) <= block.timestamp; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev getNodePort - get Node's port * @param nodeIndex - index of Node * @return port */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev isNodeLeft - checks if Node status Left * @param nodeIndex - index of Node * @return if Node status Left - true, else - false */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev getNodeNextRewardDate - get Node next reward date * @param nodeIndex - index of Node * @return Node next reward date */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes[nodeIndex].lastRewardDate.add(constantsHolder.rewardPeriod()); } /** * @dev getNumberOfNodes - get number of Nodes * @return number of Nodes */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev getNumberOfFullNodes - get number Online Nodes * @return number of active nodes plus number of leaving nodes */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev getActiveNodeIPs - get array of ips of Active Nodes * @return activeNodeIPs - array of ips of Active Nodes */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev getActiveNodesByAddress - get array of indexes of Active Nodes, which were * created by msg.sender * @return activeNodesByAddress Array of indexes of Active Nodes, which were created by msg.sender */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev getActiveNodeIds - get array of indexes of Active Nodes * @return activeNodeIds - array of indexes of Active Nodes */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev isNodeExist - checks existence of Node at this address * @param from - account address * @param nodeIndex - index of Node * @return if exist - true, else - false */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev isNodeActive - checks if Node status Active * @param nodeIndex - index of Node * @return if Node status Active - true, else - false */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev isNodeLeaving - checks if Node status Leaving * @param nodeIndex - index of Node * @return if Node status Leaving - true, else - false */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev _setNodeLeft - set Node Left * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev _setNodeLeaving - set Node Leaving * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev _addNode - adds Node to array * function could be run only by executor * @param from - owner of Node * @param name - Node name * @param ip - Node ip * @param publicIP - Node public ip * @param port - Node public port * @param publicKey - Ethereum public key * @return nodeIndex Index of Node */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } }
0x608060405234801561001057600080fd5b506004361061010a5760003560e01c806391d14854116100a2578063c2a9925611610071578063c2a9925614610204578063c4d66de814610217578063ca15c8731461022a578063d547741f1461023d578063ee8c4bbf146102505761010a565b806391d14854146101c1578063a217fddf146101e1578063b39e12cf146101e9578063be07f57c146101f15761010a565b806336568abe116100de57806336568abe1461017357806375b238fc1461018657806382dc27d71461018e5780639010d07c146101a15761010a565b806223de291461010f578063056ba37b14610124578063248a9ca3146101375780632f2ff15d14610160575b600080fd5b61012261011d36600461247a565b610263565b005b610122610132366004612548565b61048d565b61014a610145366004612548565b610d25565b604051610157919061294e565b60405180910390f35b61012261016e366004612578565b610d3d565b610122610181366004612578565b610d85565b61014a610dc7565b61012261019c3660046125c8565b610dde565b6101b46101af3660046125a7565b610ec7565b6040516101579190612774565b6101d46101cf366004612578565b610eee565b6040516101579190612943565b61014a610f0c565b6101b4610f11565b6101226101ff3660046125c8565b610f20565b610122610212366004612608565b610ff5565b610122610225366004612442565b6111e8565b61014a610238366004612548565b611320565b61012261024b366004612578565b611337565b61012261025e366004612548565b611371565b604080518082018252600a81526929b5b0b632aa37b5b2b760b11b6020808301919091526097549251919233926001600160a01b039091169163ec56a373916102ae9186910161272a565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016102e0919061294e565b60206040518083038186803b1580156102f857600080fd5b505afa15801561030c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610330919061245e565b6001600160a01b03161480610348575061034861194e565b61036d5760405162461bcd60e51b815260040161036490612e6b565b60405180910390fd5b6001600160a01b03871630146103955760405162461bcd60e51b815260040161036490612c42565b831561048257609754604051633581777360e01b81526000916001600160a01b0316906335817773906103ca90600401612a13565b60206040518083038186803b1580156103e257600080fd5b505afa1580156103f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061041a919061245e565b60405162d680f160e51b81529091506001600160a01b03821690631ad01e209061044e908c908b908b908b906004016128a1565b600060405180830381600087803b15801561046857600080fd5b505af115801561047c573d6000803e3d6000fd5b50505050505b505050505050505050565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906104bc90600401612cc2565b60206040518083038186803b1580156104d457600080fd5b505afa1580156104e8573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061050c919061245e565b609754604051633581777360e01b81529192506000916001600160a01b039091169063358177739061054090600401612ea2565b60206040518083038186803b15801561055857600080fd5b505afa15801561056c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610590919061245e565b609754604051633581777360e01b81529192506000916001600160a01b03909116906335817773906105c490600401612b70565b60206040518083038186803b1580156105dc57600080fd5b505afa1580156105f0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610614919061245e565b90506000816001600160a01b031663822a5628866040518263ffffffff1660e01b8152600401610644919061294e565b60206040518083038186803b15801561065c57600080fd5b505afa158015610670573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106949190612560565b905060006106a061194e565b8061072457506040516330d3694960e21b81526001600160a01b0384169063c34da524906106d49033908a90600401612865565b60206040518083038186803b1580156106ec57600080fd5b505afa158015610700573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107249190612528565b9050806107ad57604051630ba7341960e11b815282906001600160a01b0386169063174e683290610759903390600401612774565b60206040518083038186803b15801561077157600080fd5b505afa158015610785573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a99190612560565b1490505b806107ca5760405162461bcd60e51b815260040161036490612add565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906107f990600401612a34565b60206040518083038186803b15801561081157600080fd5b505afa158015610825573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610849919061245e565b609754604051633581777360e01b81529192506000916001600160a01b039091169063358177739061087d90600401612a7d565b60206040518083038186803b15801561089557600080fd5b505afa1580156108a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108cd919061245e565b604051630ed789cf60e41b81529091506001600160a01b0388169063ed789cf0906108fc908b9060040161294e565b600060405180830381600087803b15801561091657600080fd5b505af115801561092a573d6000803e3d6000fd5b5050604051630f3fcc6160e31b81526001600160a01b03881692506379fe6308915061095a908b9060040161294e565b60206040518083038186803b15801561097257600080fd5b505afa158015610986573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109aa9190612528565b15610a495760405163117066eb60e01b81526001600160a01b0386169063117066eb906109db908b9060040161294e565b602060405180830381600087803b1580156109f557600080fd5b505af1158015610a09573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a2d9190612528565b610a495760405162461bcd60e51b815260040161036490612f1b565b6040516305a879c360e01b8152600090819081906001600160a01b038616906305a879c390610a7c908e9060040161294e565b60206040518083038186803b158015610a9457600080fd5b505afa158015610aa8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610acc9190612560565b14610b5a57604051630893128f60e01b81526001600160a01b038a1690630893128f90610afd908d9060040161294e565b602060405180830381600087803b158015610b1757600080fd5b505af1158015610b2b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b4f9190612528565b915060019050610b5f565b600191505b8115610d195760405163a910ede360e01b81526001600160a01b0388169063a910ede390610b91908d9060040161294e565b602060405180830381600087803b158015610bab57600080fd5b505af1158015610bbf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610be39190612528565b610bff5760405162461bcd60e51b815260040161036490612c0d565b866001600160a01b031663ab4df71e8b610c9c84610c1e576000610c8f565b866001600160a01b031663c647f8446040518163ffffffff1660e01b815260040160206040518083038186803b158015610c5757600080fd5b505afa158015610c6b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c8f9190612560565b429063ffffffff61195f16565b6040518363ffffffff1660e01b8152600401610cb9929190612f60565b600060405180830381600087803b158015610cd357600080fd5b505af1158015610ce7573d6000803e3d6000fd5b5050604051630243a12360e61b81526001600160a01b038a1692506390e848c0915061044e9089908e90600401612f60565b50505050505050505050565b6000818152606560205260409020600201545b919050565b600082815260656020526040902060020154610d5b906101cf611984565b610d775760405162461bcd60e51b8152600401610364906129c4565b610d818282611988565b5050565b610d8d611984565b6001600160a01b0316816001600160a01b031614610dbd5760405162461bcd60e51b815260040161036490612ecc565b610d8182826119f7565b604051610dd390612746565b604051809103902081565b609754604051633581777360e01b81526000916001600160a01b031690633581777390610e0d90600401612a13565b60206040518083038186803b158015610e2557600080fd5b505afa158015610e39573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e5d919061245e565b604051631fa9a63560e01b81529091506001600160a01b03821690631fa9a63590610e9090339087908790600401612788565b600060405180830381600087803b158015610eaa57600080fd5b505af1158015610ebe573d6000803e3d6000fd5b50505050505050565b6000828152606560205260408120610ee5908363ffffffff611a6616565b90505b92915050565b6000828152606560205260408120610ee5908363ffffffff611a7216565b600081565b6097546001600160a01b031681565b610f2933611a87565b610f455760405162461bcd60e51b815260040161036490612dd4565b609754604051633581777360e01b81526000916001600160a01b031690633581777390610f7490600401612a13565b60206040518083038186803b158015610f8c57600080fd5b505afa158015610fa0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fc4919061245e565b604051632f81fd5f60e21b81529091506001600160a01b0382169063be07f57c90610e90908690869060040161296e565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061102490600401612b70565b60206040518083038186803b15801561103c57600080fd5b505afa158015611050573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611074919061245e565b60405163092d05f160e11b81529091506001600160a01b0382169063125a0be2906110a3903390600401612774565b600060405180830381600087803b1580156110bd57600080fd5b505af11580156110d1573d6000803e3d6000fd5b505050506110dd61238e565b6040518060c0016040528085858080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152505050908252506001600160e01b0319808a166020830152881660408083019190915261ffff8c1660608301528051808201825260809092019190889060029083908390808284376000920191909152505050815261ffff8a16602090910152604051635da6a9eb60e11b81529091506001600160a01b0383169063bb4d53d6906111ab90339085906004016127b6565b600060405180830381600087803b1580156111c557600080fd5b505af11580156111d9573d6000803e3d6000fd5b50505050505050505050505050565b600054610100900460ff16806112015750611201611c02565b8061120f575060005460ff16155b61122b5760405162461bcd60e51b815260040161036490612d1f565b600054610100900460ff16158015611256576000805460ff1961ff0019909116610100171660011790555b61125f82611c08565b609880546001600160a01b031916731820a4b7618bde71dce8cdc73aab6c95905fad2417908190556040516329965a1d60e01b81526001600160a01b0391909116906329965a1d906112d99030907fb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b90829060040161287e565b600060405180830381600087803b1580156112f357600080fd5b505af1158015611307573d6000803e3d6000fd5b505050508015610d81576000805461ff00191690555050565b6000818152606560205260408120610ee890611ca7565b600082815260656020526040902060020154611355906101cf611984565b610dbd5760405162461bcd60e51b815260040161036490612b8f565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906113a090600401612b70565b60206040518083038186803b1580156113b857600080fd5b505afa1580156113cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113f0919061245e565b6040516330d3694960e21b81529091506001600160a01b0382169063c34da524906114219033908690600401612865565b60206040518083038186803b15801561143957600080fd5b505afa15801561144d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114719190612528565b61148d5760405162461bcd60e51b815260040161036490612b2a565b6040516306e5d56360e51b81526001600160a01b0382169063dcbaac60906114b990859060040161294e565b60206040518083038186803b1580156114d157600080fd5b505afa1580156114e5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115099190612528565b6115255760405162461bcd60e51b815260040161036490612c71565b604051630f3fcc6160e31b81526001600160a01b038216906379fe63089061155190859060040161294e565b60206040518083038186803b15801561156957600080fd5b505afa15801561157d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115a19190612528565b806116235750604051635b6b418560e01b81526001600160a01b03821690635b6b4185906115d390859060040161294e565b60206040518083038186803b1580156115eb57600080fd5b505afa1580156115ff573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116239190612528565b61163f5760405162461bcd60e51b815260040161036490612e26565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061166e90600401612a5d565b60206040518083038186803b15801561168657600080fd5b505afa15801561169a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116be919061245e565b609754604051633581777360e01b8152919250600091829182916001600160a01b03909116906335817773906116f690600401612e04565b60206040518083038186803b15801561170e57600080fd5b505afa158015611722573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611746919061245e565b60405163192f1ecd60e31b81529091506001600160a01b0382169063c978f6689061177590899060040161294e565b6040805180830381600087803b15801561178e57600080fd5b505af11580156117a2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117c691906126a9565b6040516301cfc27160e21b815291945092506000906001600160a01b0386169063073f09c4906117fe908a9088908890600401612f6e565b602060405180830381600087803b15801561181857600080fd5b505af115801561182c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118509190612560565b604051638d3a0f1960e01b81529091506001600160a01b03871690638d3a0f199061187f908a9060040161294e565b600060405180830381600087803b15801561189957600080fd5b505af11580156118ad573d6000803e3d6000fd5b5050505060008111156119415761193f81876001600160a01b031663822a56288a6040518263ffffffff1660e01b81526004016118ea919061294e565b60206040518083038186803b15801561190257600080fd5b505afa158015611916573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061193a9190612560565b611cb2565b505b610ebe8733868685611e80565b600061195a8133610eee565b905090565b600082820183811015610ee55760405162461bcd60e51b815260040161036490612aa6565b3390565b60008281526065602052604090206119a6908263ffffffff61202d16565b15610d81576119b3611984565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000828152606560205260409020611a15908263ffffffff61204216565b15610d8157611a22611984565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b6000610ee58383612057565b6000610ee5836001600160a01b03841661209c565b60975460405160009182916001600160a01b039091169063ec56a37390611ab09060200161275c565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611ae2919061294e565b60206040518083038186803b158015611afa57600080fd5b505afa158015611b0e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b32919061245e565b90506001600160a01b03811615611bf2576000819050806001600160a01b03166391d14854604051611b6390612746565b6040519081900381206001600160e01b031960e084901b168252611b8b918890600401612957565b60206040518083038186803b158015611ba357600080fd5b505afa158015611bb7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bdb9190612528565b80611be95750611be961194e565b92505050610d38565b611bfa61194e565b915050610d38565b303b1590565b600054610100900460ff1680611c215750611c21611c02565b80611c2f575060005460ff16155b611c4b5760405162461bcd60e51b815260040161036490612d1f565b600054610100900460ff16158015611c76576000805460ff1961ff0019909116610100171660011790555b611c7e6120b4565b611c89600033610d77565b611c9282612147565b8015610d81576000805461ff00191690555050565b6000610ee8826121bd565b609754604051633581777360e01b815260009182916001600160a01b0390911690633581777390611ce590600401612c9e565b60206040518083038186803b158015611cfd57600080fd5b505afa158015611d11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d35919061245e565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390611d6990600401612d6d565b60206040518083038186803b158015611d8157600080fd5b505afa158015611d95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611db9919061245e565b9050816001600160a01b031663dcdc7dd0828787604051602001611ddd919061294e565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401611e0a939291906128c9565b602060405180830381600087803b158015611e2457600080fd5b505af1158015611e38573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e5c9190612528565b611e785760405162461bcd60e51b815260040161036490612bdf565b505092915050565b609754604051633581777360e01b81526000916001600160a01b031690633581777390611eaf90600401612e04565b60206040518083038186803b158015611ec757600080fd5b505afa158015611edb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611eff919061245e565b90506000816001600160a01b03166355635b17886040518263ffffffff1660e01b8152600401611f2f919061294e565b60206040518083038186803b158015611f4757600080fd5b505afa158015611f5b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f7f9190612560565b604051631c251c6f60e01b81529091506001600160a01b03831690631c251c6f90611fae908a9060040161294e565b600060405180830381600087803b158015611fc857600080fd5b505af1158015611fdc573d6000803e3d6000fd5b50505050867f2dcc32dc31fb404a56cb0900d440e84d56b4d3b649cee8df3287f095a48939d38787878786425a60405161201c9796959493929190612908565b60405180910390a250505050505050565b6000610ee5836001600160a01b0384166121c1565b6000610ee5836001600160a01b03841661220b565b8154600090821061207a5760405162461bcd60e51b815260040161036490612982565b82600001828154811061208957fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600054610100900460ff16806120cd57506120cd611c02565b806120db575060005460ff16155b6120f75760405162461bcd60e51b815260040161036490612d1f565b600054610100900460ff16158015612122576000805460ff1961ff0019909116610100171660011790555b61212a6122d1565b6121326122d1565b8015612144576000805461ff00191690555b50565b6001600160a01b03811661216d5760405162461bcd60e51b815260040161036490612d92565b61217f816001600160a01b0316612352565b61219b5760405162461bcd60e51b815260040161036490612ce8565b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b60006121cd838361209c565b61220357508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610ee8565b506000610ee8565b600081815260018301602052604081205480156122c7578354600019808301919081019060009087908390811061223e57fe5b906000526020600020015490508087600001848154811061225b57fe5b60009182526020808320909101929092558281526001898101909252604090209084019055865487908061228b57fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050610ee8565b6000915050610ee8565b600054610100900460ff16806122ea57506122ea611c02565b806122f8575060005460ff16155b6123145760405162461bcd60e51b815260040161036490612d1f565b600054610100900460ff16158015612132576000805460ff1961ff0019909116610100171660011790558015612144576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061238657508115155b949350505050565b6040805160c0810182526060808252600060208301819052928201839052810191909152608081016123be6123cb565b8152600060209091015290565b60405180604001604052806002906020820280368337509192915050565b60008083601f8401126123fa578182fd5b50813567ffffffffffffffff811115612411578182fd5b60208301915083602082850101111561242957600080fd5b9250929050565b803561ffff81168114610ee857600080fd5b600060208284031215612453578081fd5b8135610ee581612fb4565b60006020828403121561246f578081fd5b8151610ee581612fb4565b60008060008060008060008060c0898b031215612495578384fd5b88356124a081612fb4565b975060208901356124b081612fb4565b965060408901356124c081612fb4565b955060608901359450608089013567ffffffffffffffff808211156124e3578586fd5b6124ef8c838d016123e9565b909650945060a08b0135915080821115612507578384fd5b506125148b828c016123e9565b999c989b5096995094979396929594505050565b600060208284031215612539578081fd5b81518015158114610ee5578182fd5b600060208284031215612559578081fd5b5035919050565b600060208284031215612571578081fd5b5051919050565b6000806040838503121561258a578182fd5b82359150602083013561259c81612fb4565b809150509250929050565b600080604083850312156125b9578182fd5b50508035926020909101359150565b600080602083850312156125da578182fd5b823567ffffffffffffffff8111156125f0578283fd5b6125fc858286016123e9565b90969095509350505050565b600080600080600080600060e0888a031215612622578283fd5b61262c8989612430565b965061263b8960208a01612430565b9550604088013561264b81612fc9565b9450606088013561265b81612fc9565b935060c088018981111561266d578384fd5b608089019350803567ffffffffffffffff811115612689578384fd5b6126958b828c016123e9565b999c989b5096995094979396939450505050565b600080604083850312156126bb578182fd5b505080516020909101519092909150565b60008284528282602086013780602084860101526020601f19601f85011685010190509392505050565b6000815180845261270e816020860160208601612f84565b601f01601f19169290920160200192915050565b61ffff169052565b6000825161273c818460208701612f84565b9190910192915050565b6941444d494e5f524f4c4560b01b8152600a0190565b6b29b5b0b632a6b0b730b3b2b960a11b8152600c0190565b6001600160a01b0391909116815260200190565b6001600160a01b03841681526040602082018190526000906127ad90830184866126cc565b95945050505050565b600060018060a01b03841682526020604081840152835160e060408501526127e26101208501826126f6565b858301516001600160e01b031990811660608781019190915260408801519091166080808801919091529087015161ffff1660a087015286015184925060c08601905b6002841015612844578051825260019390930192908401908401612825565b505060a0860151925061285b610100860184612722565b9695505050505050565b6001600160a01b03929092168252602082015260400190565b6001600160a01b0393841681526020810192909252909116604082015260600190565b600060018060a01b03861682528460208301526060604083015261285b6060830184866126cc565b600060018060a01b0385168252836020830152608060408301526128f060808301846126f6565b82810360609093019290925281526020019392505050565b6001600160a01b03979097168752602087019590955260408601939093526060850191909152608084015260a083015260c082015260e00190565b901515815260200190565b90815260200190565b9182526001600160a01b0316602082015260400190565b6000602082526123866020830184866126cc565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526007908201526653636861696e7360c81b604082015260600190565b6020808252600f908201526e14d8da185a5b9cd25b9d195c9b985b608a1b604082015260600190565b602080825260069082015265426f756e747960d01b604082015260600190565b6020808252600f908201526e21b7b739ba30b73a39a437b63232b960891b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6020808252602d908201527f53656e646572206973206e6f74207065726d697474656420746f2063616c6c2060408201526c3a3434b990333ab731ba34b7b760991b606082015260800190565b60208082526026908201527f4e6f646520646f6573206e6f7420657869737420666f72204d6573736167652060408201526539b2b73232b960d11b606082015260800190565b6020808252600590820152644e6f64657360d81b604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b602080825260149082015273151bdad95b881dd85cc81b9bdd081b5a5b9d195960621b604082015260600190565b6020808252818101527f46696e697368696e67206f66206e6f64652065786974206973206661696c6564604082015260600190565b602080825260159082015274149958d95a5d995c881a5cc81a5b98dbdc9c9958dd605a1b604082015260600190565b6020808252601390820152724e6f742074696d6520666f7220626f756e747960681b604082015260600190565b6020808252600a908201526929b5b0b632aa37b5b2b760b11b604082015260600190565b6020808252600c908201526b2737b232a937ba30ba34b7b760a11b604082015260600190565b60208082526017908201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252600b908201526a2234b9ba3934b13aba37b960a91b604082015260600190565b60208082526022908201527f436f6e74726163744d616e616765722061646472657373206973206e6f742073604082015261195d60f21b606082015260800190565b60208082526016908201527521b0b63632b91034b9903737ba1030b71030b236b4b760511b604082015260600190565b6020808252600890820152674d6f6e69746f727360c01b604082015260600190565b60208082526025908201527f4e6f6465206973206e6f742041637469766520616e64206973206e6f74204c656040820152646176696e6760d81b606082015260800190565b60208082526019908201527f4d6573736167652073656e64657220697320696e76616c696400000000000000604082015260600190565b60208082526010908201526f56616c696461746f725365727669636560801b604082015260600190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b60208082526025908201527f496e697469616c697a6174696f6e206f66206e6f646520657869742069732066604082015264185a5b195960da1b606082015260800190565b918252602082015260400190565b9283526020830191909152604082015260600190565b60005b83811015612f9f578181015183820152602001612f87565b83811115612fae576000848401525b50505050565b6001600160a01b038116811461214457600080fd5b6001600160e01b03198116811461214457600080fdfea2646970667358221220bebf3ad3942a7d3405260ec8c602f6261044de23a25bf7eca9169635270e7c6664736f6c634300060a0033
[ 0, 4, 7, 9, 6, 10 ]
0x5c3da04441a2b301a4663b8f3922d7f794792041
pragma solidity 0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract TVT is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function TVT( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a723058206e6a008ad02f0423ebeae5609c95f11cc6ce3f7a0cccc74da6373a7b5a150a1a0029
[ 38 ]
0x5c51ed459af01dc9857a70d8630a383d394ec66d
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract IAbacusOracle{ uint public callFee; function getJobResponse(uint64 _jobId) public view returns(uint64[] memory _values){ } function scheduleFunc(address to ,uint callTime, bytes memory data , uint fee , uint gaslimit ,uint gasprice)public payable{} } 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; } 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; } } 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()); } } } contract ERC20Basic { uint public _totalSupply; string public name; string public symbol; uint public decimals; function totalSupply() public view returns (uint){} function balanceOf(address who) public view returns (uint){} function transfer(address to, uint value) public {} function transferFrom(address _from, address _to, uint _value) public{} function approve(address spender, uint amount) public {} function allowance(address _owner, address _spender) public view returns (uint remaining) {} event Transfer(address indexed from, address indexed to, uint value); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => uint256) public lockedAmount; 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,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. 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 availableAmount(address owner) public view returns(uint256){ return balanceOf(owner).sub(lockedAmount[owner]); } 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"); require(amount <= availableAmount(sender),"ERC20 : amount exceeds available amount"); _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"); require(amount <= availableAmount(account),"ERC20 : burn exceeds available amount"); _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"); require(amount <= availableAmount(owner),"ERC20 : approve amount exceeds available amount"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _lock(address owner,uint256 amount) internal virtual { require(owner != address(0), "ERC20: lock for zero address"); require(amount <= availableAmount(owner),"ERC20: lock value more tha available amount"); lockedAmount[owner] = lockedAmount[owner].add(amount); } function _release(address owner,uint256 amount) internal virtual{ require(owner != address(0), "ERC20: release for zero address"); require(amount <= lockedAmount[owner],"ERC20 : release value more then locked value"); lockedAmount[owner] = lockedAmount[owner].sub(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 { } } 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); } } } } 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)); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * 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()); } } 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"); } } contract wERC20 is Context, AccessControl, ERC20, ERC20Pausable { bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant ETMOWNER_ROLE = keccak256("ETM_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,uint8 decimals,address admin,address etmOwner) public ERC20(name, symbol,decimals) { _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(ETMOWNER_ROLE, etmOwner); _setupRole(MINTER_ROLE, admin); _setupRole(PAUSER_ROLE, admin); } /** * @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); } function burnFrom(address _from,uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to burn"); _burn(_from,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(); } function changeAdmin(address admin) public virtual{ require(hasRole(ETMOWNER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role"); _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(MINTER_ROLE, admin); _setupRole(PAUSER_ROLE, admin); } /** * @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 lock(address account , uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to lock"); _lock(account,amount); } function release(address account , uint256 amount) public virtual{ require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have admin role to release"); _release(account,amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) { super._beforeTokenTransfer(from, to, amount); } } nt) public orderUSDValue; /*=========Structs and Initializer================ --------------------------------*/ struct freeStorage{ //USER DEPOSIT / BORROW STRUCTURE uint amount; uint time; string wtoken; uint usdvalue; } struct matchedOrder{ //RUNNING OR MATCHED ORDERS IN THIS FORM address supplier; address borrower; uint time; uint expiryDate; uint duration; uint amount; uint usdvalue; uint yield; string wtoken; uint duesPaid; } struct Order{ // PENDING ORDERS IN THIS FORMAT address creator; uint duration; uint amount; uint yield; string wtoken; } struct User{ uint totalDeposit; //USD VALUE OF TOTAL DEPOSIT AT DEPOSIT TIME uint totalBorrowed; //USD VALUE OF TOTAL DEPOSIT AT BORROW TIME freeStorage [] myDeposits; //DEPOSIT DATA freeStorage [] myBorrows; //BORROW DATA mapping(string => uint) deposits; //CURRENCY-WISE TOTAL DEPOSIT COUNT FULL VALUE mapping(string => uint) borrows; //CURRENCY-WISE TOTAL BORROW COUNT FULL VALUE uint64 [] borrowedOrders; //BORROWED ORDER - ORDER ID uint64 [] createdOrders; //CREATED ORDER - ORDER ID uint64 [] myOrders; //MATCHED ORDR - ORDER ID } function initializeAddress(address payable EMMaddress,address AbacusAddress, address payable Initaddress) external initializer{ EMM = EcoMoneyManager(EMMaddress); abacus = IAbacusOracle(AbacusAddress); Init = EcoceliumInit(Initaddress); } /*============Main Functions=============== Key Notes - 1) Always call main functions of Data Manager with Wrapped Token 2) _status signifies (status == Status.OPENCREATOR) operation - Returns True for Deposit Functions and False for Borrow Function 3) require(Init.friendlyaddress(msg.sender) ,"Not Friendly Address"); - This is mentioned in the EcoceliumInit Contract 4) FreePusher/Popper are for Liquidity Pools and push/pop order and matchOrder is the Order Matching Engine 5) Fetch Token Price Returns Values in 10**8 6) Amounts are without setting off Token Decimals ---------------------------------*/ function freePusher(address userAddress, string memory token, uint _amount, bool _status) external { //_status signifies (status == Status.OPENCREATOR) operation require(Init.friendlyaddress(msg.sender) ,"Not Friendly Address"); uint _usdValue = USDValue(_amount, token); freeStorage memory newStorage = freeStorage({ amount: _amount, time: now, wtoken: token, usdvalue: _usdValue }); if(_status){ users[userAddress].myDeposits.push(newStorage); users[userAddress].totalDeposit += _usdValue; users[userAddress].deposits[token] += _amount; } else { users[userAddress].myBorrows.push(newStorage); users[userAddress].totalBorrowed += _usdValue; users[userAddress].borrows[token] += _amount; } } function freePopper(address userAddress, string memory _tokenSymbol, uint _amount, bool _status) public returns (uint dues) { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); if(_status) { require(users[userAddress].deposits[_tokenSymbol]>=_amount, "Insufficient Deposits"); users[userAddress].deposits[_tokenSymbol] -= _amount; } else { require(users[userAddress].borrows[_tokenSymbol]>=_amount,"Insufficient Borrowings"); users[userAddress].borrows[_tokenSymbol] -= _amount; } uint amountLeft= _amount; freeStorage [] storage mystorage = _status ? users[userAddress].myDeposits : users[userAddress].myBorrows; for( uint i= mystorage.length-1; amountLeft >0 ; i--){ if(keccak256(abi.encodePacked(mystorage[i].wtoken)) != keccak256(abi.encodePacked(_tokenSymbol))) { continue; } if (mystorage[i].amount <= amountLeft){ amountLeft -= mystorage[i].amount; _status ? users[userAddress].totalDeposit -= mystorage[i].usdvalue : users[userAddress].totalBorrowed -= mystorage[i].usdvalue; dues+= calculateECOEarning(USDValue(mystorage[i].amount,_tokenSymbol), _tokenSymbol, mystorage[i].time); mystorage.pop(); } else { _status ? users[userAddress].totalDeposit -= (mystorage[i].amount-amountLeft)*mystorage[i].usdvalue : users[userAddress].totalBorrowed -= (mystorage[i].amount-amountLeft)*mystorage[i].usdvalue; mystorage[i].amount -= amountLeft; dues += calculateECOEarning(USDValue(amountLeft,_tokenSymbol), _tokenSymbol, mystorage[i].time); amountLeft = 0; } } _status ? users[userAddress].myDeposits = mystorage : users[userAddress].myBorrows = mystorage; } function pushOrder(address userAddress,string memory _tokenSymbol ,uint _amount,uint _duration, uint _yield, bool _status) internal returns (uint){ (uint64 _orderId,uint newAmount,uint fee) = _ordersub(_amount,userAddress,_duration,_tokenSymbol); openOrderMap[_orderId] = Order({ creator : userAddress, duration : _duration, amount : newAmount, yield : _yield, wtoken : _tokenSymbol }); if(_status) { orderStatus[_orderId] = Status.OPENCREATOR; users[userAddress].createdOrders.push(_orderId); } else { orderStatus[_orderId] = Status.OPENBORROW; users[userAddress].borrowedOrders.push(_orderId); } poolSorter(_orderId, _tokenSymbol, true); orderUSDValue[_orderId]=USDValue(_amount,_tokenSymbol); return fee; } function poolSorter(uint64 _orderId, string memory _tokenSymbol, bool _status) internal { //Status here signifies Insertion if True, and Deletion if false uint64 [] memory temp; bool task; poolindex[_tokenSymbol]=0; if(orderpool[_tokenSymbol].length==0 && _status) { orderpool[_tokenSymbol][0] = _orderId; } for((uint i, uint j)=(0,0);i<orderpool[_tokenSymbol].length;(i++,j++)) { temp[j]=orderpool[_tokenSymbol][i]; if(!task && _status && openOrderMap[temp[j]].yield > openOrderMap[_orderId].yield) { //Insertion Case temp[j]=_orderId; temp[++j]=orderpool[_tokenSymbol][i]; task = true; }else if(!task && !_status && _orderId == temp[j]){ //Deletion Case temp[j]=orderpool[_tokenSymbol][++i]; task = true; } if(orderStatus[orderpool[_tokenSymbol][i-1]]==Status.OPENBORROW && orderStatus[orderpool[_tokenSymbol][i]]==Status.OPENCREATOR) { //Assigns updatePoolIndex poolindex[_tokenSymbol] = i; break; } } orderpool[_tokenSymbol] = temp; } function matchOrder(address userAddress, string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield, uint64 _orderId, bool _status) internal { matchOrderMap[_orderId] = matchedOrder({ supplier : (orderStatus[_orderId] == Status.OPENBORROW) ? userAddress : openOrderMap[_orderId].creator, borrower : (orderStatus[_orderId] == Status.OPENCREATOR) ? userAddress : openOrderMap[_orderId].creator, time : now, expiryDate : now + _duration*(30 days), duration : _duration, amount : _amount, usdvalue : USDValue(_amount,_tokenSymbol), yield : _yield, wtoken : _tokenSymbol, duesPaid : 0 }); _status ? delete users[openOrderMap[_orderId].creator].borrowedOrders[_orderId] : delete users[userAddress].createdOrders[_orderId]; delete openOrderMap[_orderId]; orderStatus[_orderId]=Status.MATCHED; orderUSDValue[_orderId]=USDValue(_amount,_tokenSymbol); users[matchOrderMap[_orderId].supplier].myOrders.push(_orderId); users[matchOrderMap[_orderId].borrower].myOrders.push(_orderId); scheduleExpiry(_orderId); scheduleCheck(_orderId,matchOrderMap[_orderId].borrower,1); EMM.mintWrappedToken(matchOrderMap[_orderId].borrower, _amount, _tokenSymbol); Init.emitOrderCreated(userAddress,_duration,_yield,_amount,_tokenSymbol); } function newOrder(address userAddress,string memory _tokenSymbol ,uint _amount,uint _duration, uint _yield, bool _status) external { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); uint amountLeft= _amount; uint index; if(_status){ index = poolindex[_tokenSymbol]-1; users[userAddress].deposits[_tokenSymbol] +=_amount; users[userAddress].totalDeposit += USDValue(_amount, _tokenSymbol); } else { index = poolindex[_tokenSymbol]; users[userAddress].borrows[_tokenSymbol] +=_amount; users[userAddress].totalBorrowed += USDValue(_amount, _tokenSymbol); } while(amountLeft>0){ if(poolindex[_tokenSymbol] == 0) { pushOrder(userAddress, _tokenSymbol, _amount, _duration, _yield, _status); break; } Order memory iOrder = openOrderMap[orderpool[_tokenSymbol][index]]; if((_status && _yield>iOrder.yield) || (!_status && _yield<iOrder.yield) || (_status)?(orderStatus[orderpool[_tokenSymbol][index]] == Status.OPENCREATOR):(orderStatus[orderpool[_tokenSymbol][index]] == Status.OPENBORROW)){ pushOrder(userAddress, _tokenSymbol, _amount, _duration, _yield, _status); break; } else { uint tduration = _duration > iOrder.duration ? _duration : iOrder.duration; uint tyield = _yield > iOrder.yield ? iOrder.yield : _yield; uint64 tID = orderpool[_tokenSymbol][index]; if(iOrder.amount>=amountLeft) { if(iOrder.amount != amountLeft) { pushOrder(iOrder.creator, _tokenSymbol, iOrder.amount-amountLeft, iOrder.duration, iOrder.yield, !_status); } matchOrder(userAddress, _tokenSymbol, amountLeft, tduration, tyield, tID, _status); amountLeft=0; } else { pushOrder(userAddress, _tokenSymbol, amountLeft- iOrder.amount, _duration, _yield, _status); matchOrder(userAddress, _tokenSymbol, amountLeft, tduration, tyield, tID , _status); amountLeft -= openOrderMap[orderpool[_tokenSymbol][index]].amount; } } } } function orderExpired (uint64 _orderId) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); require (matchOrderMap[_orderId].expiryDate <= now); EMM.releaseWrappedToken(matchOrderMap[_orderId].supplier,matchOrderMap[_orderId].amount, matchOrderMap[_orderId].wtoken); users[matchOrderMap[_orderId].supplier].totalDeposit -= matchOrderMap[_orderId].usdvalue; users[matchOrderMap[_orderId].borrower].totalBorrowed -= matchOrderMap[_orderId].usdvalue; orderStatus[_orderId] = Status.CLOSED; //Init.OrderExpired(_orderId,msgSender,orderMonthlyDue(_orderId,msgSender,_duration)); } function payDue(uint64 _orderId,uint _duration,address msgSender) external returns (uint due){ due = orderMonthlyDue(_orderId,_duration); uint fee = (due*Init.rewardFee())/100; EMM.DepositManager(Init.ECO(), due+fee, msgSender); Init.setOwnerFeeVault(Init.WRAP_ECO_SYMBOL(), fee); matchOrderMap[_orderId].duesPaid += 1; matchOrderMap[_orderId].duesPaid >= uint((now - matchOrderMap[_orderId].time)/30 days) ? Init.setUserLocked(msgSender,false) : Init.setUserLocked(msgSender,true); Init.emitDuePaid(_orderId,msgSender,orderMonthlyDue(_orderId,_duration)); } function dueCheck(uint64 _orderId,address borrower,uint month) external returns(uint) { require (Init.friendlyaddress(msg.sender) && now >= matchOrderMap[_orderId].time + matchOrderMap[_orderId].duesPaid * 30 days); uint due = orderMonthlyDue(_orderId,1); EMM.mintECO(matchOrderMap[_orderId].supplier,due*(100-Init.rewardFee())/100); if(matchOrderMap[_orderId].duesPaid < month && !Init.isRegistrar(borrower) && !Init.isUserLocked(borrower)){ Init.setUserLocked(borrower,true); orderExpired(_orderId); } else { Init.emitDuePaid(_orderId,borrower,orderMonthlyDue(_orderId,month+1)); scheduleCheck(_orderId,borrower,month+1); } } function scheduleExpiry(uint64 _orderId) internal{ uint time = matchOrderMap[_orderId].expiryDate - matchOrderMap[_orderId].time; bytes memory data = abi.encodeWithSelector(bytes4(keccak256('orderExpired(uint256)')),_orderId); uint callCost = 300000*1e9 + abacus.callFee(); abacus.scheduleFunc{value:callCost}(address(this), time ,data , abacus.callFee() ,300000 , 1e9 ); } function scheduleCheck(uint _orderId,address borrower,uint month) internal{ bytes memory data = abi.encodeWithSelector(bytes4(keccak256('dueCheck(uint256,address,uint256)')),_orderId,borrower,month); uint callCost = 300000*1e9 + abacus.callFee(); abacus.scheduleFunc{value:callCost}(address(this), 30 days ,data , abacus.callFee() ,300000 , 1e9 ); } function cancelOrder(uint64 _orderId) external{ require(Init.friendlyaddress(msg.sender)); if(orderStatus[_orderId]==Status.OPENCREATOR) { EMM.releaseWrappedToken(openOrderMap[_orderId].creator,openOrderMap[_orderId].amount, openOrderMap[_orderId].wtoken); users[openOrderMap[_orderId].creator].deposits[openOrderMap[_orderId].wtoken] -=openOrderMap[_orderId].amount; users[openOrderMap[_orderId].creator].totalDeposit -= orderUSDValue[_orderId]; for((uint i,uint j)=(0,0); i<users[openOrderMap[_orderId].creator].createdOrders.length; (i++,j++)) { if(users[openOrderMap[_orderId].creator].createdOrders[i] == _orderId) { --j; continue; } users[openOrderMap[_orderId].creator].createdOrders[j] = users[openOrderMap[_orderId].creator].createdOrders[i]; } } else if(orderStatus[_orderId]==Status.OPENBORROW){ users[openOrderMap[_orderId].creator].borrows[openOrderMap[_orderId].wtoken] -=openOrderMap[_orderId].amount; users[openOrderMap[_orderId].creator].totalBorrowed -= orderUSDValue[_orderId]; for((uint i,uint j)=(0,0); i<users[openOrderMap[_orderId].creator].borrowedOrders.length; (i++,j++)) { if(users[openOrderMap[_orderId].creator].borrowedOrders[i] == _orderId) { continue; } users[openOrderMap[_orderId].creator].borrowedOrders[j] = users[openOrderMap[_orderId].creator].borrowedOrders[i]; } } poolSorter(_orderId, openOrderMap[_orderId].wtoken,false); delete openOrderMap[_orderId]; delete orderUSDValue[_orderId]; orderStatus[_orderId] = Status.CLOSED; } /*==============Helpers============ ---------------------------------*/ function USDValue(uint amount, string memory _token) public view returns (uint usdvalue) { usdvalue = amount*fetchTokenPrice(_token)/(10**8)/(10**uint(wERC20(EMM.getwTokenAddress(_token)).decimals())); } function orderMonthlyDue(uint64 _orderId, uint _duration) public view returns(uint due){ orderStatus[_orderId] == Status.MATCHED ? due = USDValue (matchOrderMap[_orderId].amount, matchOrderMap[_orderId].wtoken) * matchOrderMap[_orderId].yield * _duration*30 days*fetchTokenPrice(Init.WRAP_ECO_SYMBOL())/3153600000/(10**8) : due = 0; } function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint){ //Put any Token Wrapped or Direct uint response = uint(abacus.getJobResponse(EMM.getFetchId(_tokenSymbol))[0]); return response > 0 ? response : 0; } /*function issueReward(address userAddress, string memory _tokenSymbol, uint time, uint tokenUsdValue) internal { uint reward = calculateECOEarning(tokenUsdValue, _tokenSymbol, time); EMM.mintECO(userAddress, reward); }*/ function calculateECOEarning(uint usdvalue, string memory _tokenSymbol, uint time) private view returns (uint){ uint _amount = usdvalue*(10**16)/fetchTokenPrice(Init.WRAP_ECO_SYMBOL()); uint reward = (_amount * Init.slabRateDeposit(_tokenSymbol) * (now - time))/3153600000; //decimal from Abacus is setoff by decimal from Eco return reward; } function getECOEarnings(address userAddress) public view returns (uint){ uint ecobalance; for(uint i=0; i<users[userAddress].myDeposits.length; i++) { ecobalance += calculateECOEarning(users[userAddress].myDeposits[i].usdvalue, users[userAddress].myDeposits[i].wtoken, users[userAddress].myDeposits[i].time); } for(uint i=0; i<users[userAddress].myBorrows.length; i++) { ecobalance -= calculateECOEarning(users[userAddress].myBorrows[i].usdvalue, users[userAddress].myBorrows[i].wtoken, users[userAddress].myBorrows[i].time); } return ecobalance - EMM.ecoWithdrawls(userAddress); } function _ordersub(uint amount,address userAddress,uint _duration,string memory _tokenSymbol) internal view returns (uint64, uint, uint){ uint newAmount = amount - (amount*Init.tradeFee())/100; uint fee = (amount*Init.tradeFee())/100; uint64 _orderId = uint64(uint(keccak256(abi.encodePacked(userAddress,_tokenSymbol,_duration,now)))); return (_orderId,newAmount,fee); } function getUserDepositsbyToken(address userAddress, string memory wtoken) public view returns(uint) { return users[userAddress].deposits[wtoken]; } function getUserBorrowedOrderbyToken(address userAddress, string memory wtoken) public view returns(uint) { return users[userAddress].borrows[wtoken]; } function getUserBorrowed(address userAddress) public view returns(uint) { return users[userAddress].totalBorrowed; } function getUserBorrowedOrder(address userAddress) public view returns (uint64 [] memory) { return users[userAddress].borrowedOrders; } function getUserDepositOrder(address userAddress) public view returns (uint64 [] memory) { return users[userAddress].createdOrders; } function getUserMatchOrder(address userAddress) public view returns (uint64 [] memory) { return users[userAddress].myOrders; } function getbuyPower(address userAddress) public view returns (uint){ if(!Init.isRegistrar(userAddress)) { return (10**30); } if(Init.isUserLocked(userAddress)) { return 0; } uint buyPower; buyPower += users[userAddress].totalDeposit - ((users[userAddress].totalDeposit*Init.CDSpercent())/100); buyPower -= users[userAddress].totalBorrowed; return buyPower; } function getOrderIds(string memory wtoken) public view returns (uint64 [] memory orderIds) { return orderpool[wtoken]; } } contract Ecocelium is Initializable{ address public owner; address payable EMMAddress; IAbacusOracle abacus; EcoMoneyManager EMM; EcoceliumDataManager EDM; EcoceliumInit Init; function initialize(address _owner,address payable EMMaddress,address payable AbacusAddress,address EDMaddress, address payable Initaddress)public payable initializer { owner = _owner; EMM = EcoMoneyManager(EMMaddress); EMMAddress = EMMaddress; abacus = IAbacusOracle(AbacusAddress);//0x323f81D9F57d2c3d5555b14d90651aCDc03F9d52 EDM = EcoceliumDataManager(EDMaddress); Init = EcoceliumInit(Initaddress); } function changeOwner(address _owner) public{ require(msg.sender==owner); owner = _owner; } func pdateContracts() public{ require(msg.sender==owner); EMM = EcoMoneyManager(Init.MONEYMANAGER()); abacus = IAbacusOracle(Init.ABACUS()); EDM = EcoceliumDataManager(Init.DATAMANAGER()); } /*===========Main functions============ -------------------------------------*/ function Deposit(string memory rtoken, uint _amount) external payable { address _msgSender = msg.sender; string memory wtoken = EMM.getWrapped(rtoken); _deposit(rtoken, _amount, _msgSender, wtoken); EDM.freePusher(_msgSender, wtoken, _amount, true); EMM.mintWrappedToken(_msgSender, _amount, wtoken); EMM.lockWrappedToken(_msgSender, _amount,wtoken); } function _deposit(string memory rtoken,uint _amount, address msgSender, string memory wtoken) internal { require(EMM.getwTokenAddress(wtoken) != address(0),"not supported"); if(keccak256(abi.encodePacked(rtoken)) == keccak256(abi.encodePacked(Init.ETH_SYMBOL()))) { require(msg.value >= _amount); EMM.DepositManager{value:msg.value}(rtoken, _amount, msgSender); }else { EMM.DepositManager(rtoken, _amount, msgSender); } Init.emitSwap(msgSender,rtoken,wtoken,_amount); } function depositAndOrder(address userAddress,string memory rtoken ,uint _amount,uint _duration,uint _yield) external payable { require(msg.sender == userAddress); string memory wtoken = EMM.getWrapped(rtoken); _deposit(rtoken, _amount, userAddress, wtoken); EMM.mintWrappedToken(userAddress, _amount, wtoken); EMM.lockWrappedToken(userAddress, _amount,wtoken); EDM.newOrder(userAddress, EMM.getWrapped(rtoken), _amount, _duration, _yield, true); } function createOrder(address userAddress,string memory _tokenSymbol ,uint _amount,uint _duration,uint _yield) external payable { require(msg.sender == userAddress); string memory wtoken = EMM.getWrapped(_tokenSymbol); require(EDM.getUserDepositsbyToken(userAddress, wtoken) >= _amount, "Insufficient Balance"); uint ecoEarnings = EDM.freePopper(userAddress, wtoken , _amount, true); if(ecoEarnings > EMM.ecoWithdrawls(userAddress)) { ecoEarnings-=EMM.ecoWithdrawls(userAddress); EMM.adjustEcoEarning(userAddress, EMM.ecoWithdrawls(userAddress)); EMM.mintECO(userAddress, ecoEarnings); } else { EMM.adjustEcoEarning(userAddress, ecoEarnings); } EDM.newOrder(userAddress, wtoken, _amount, _duration, _yield, true); } function getAggEcoBalance(address userAddress) public view returns(uint) { return wERC20(EMM.getwTokenAddress(Init.WRAP_ECO_SYMBOL())).balanceOf(userAddress) + EDM.getECOEarnings(userAddress); } function borrowOrder(address userAddress, string memory rtoken, uint amount, uint duration, uint yield) public {//Rewrite this part require(isWithdrawEligible(userAddress, rtoken, amount)); EDM.newOrder(msg.sender,rtoken, amount,duration,yield,false); } function payDueOrder(uint64 _orderId,uint _duration) external { EDM.payDue(_orderId,_duration,msg.sender); } function clearBorrow(string memory rtoken, uint _amount) external payable{ address msgSender = msg.sender; string memory wtoken = EMM.getWrapped(rtoken); uint dues = EDM.freePopper(msgSender, wtoken, _amount, false); EMM.DepositManager(Init.ECO(), dues, msgSender); if(keccak256(abi.encodePacked(rtoken)) == keccak256(abi.encodePacked(Init.ETH_SYMBOL()))) { require(msg.value == _amount); EMM.DepositManager{value:_amount}(rtoken, _amount, msgSender); }else { EMM.DepositManager(rtoken, _amount, msgSender); } } function Borrow(address payable userAddress, uint _amount, string memory _tokenSymbol) public { require(userAddress == msg.sender); require(isWithdrawEligible(userAddress, _tokenSymbol, _amount)); EDM.freePusher(msg.sender, EMM.getWrapped(_tokenSymbol), _amount,false); EMM.WithdrawManager(_tokenSymbol, _amount, userAddress); } function SwapWrapToWrap(string memory token1,string memory token2, uint token1amount) external returns(uint) { address msgSender = msg.sender; uint token2price = fetchTokenPrice(token2); uint token2amount = EDM.USDValue(token1amount,token1)*(100-Init.swapFee())*(10**uint(wERC20(EMM.getwTokenAddress(token2)).decimals()))*(10**8)/token2price/100; EMM.w2wswap(msgSender, token1, token1amount, token2amount, token2); uint ecoEarnings = EDM.freePopper(msgSender,token1,token1amount,true); EMM.mintECO(msgSender, ecoEarnings); Init.setOwnerFeeVault(token1, token1amount*Init.swapFee()/100); EDM.freePusher(msgSender, token2,token2amount,true); Init.emitSwap(msgSender,token1,token2,token2amount); return token2amount; } function cancelOrder(uint64 _orderId) public{ (address creator,,,,) = EDM.openOrderMap(_orderId); require(msg.sender==creator); EDM.cancelOrder(_orderId); } receive() external payable { } /*==============Helpers============ ---------------------------------*/ function orderMonthlyDue(uint64 _orderId,uint _duration) public view returns(uint){ return EDM.orderMonthlyDue(_orderId,_duration); } function updateFees(uint _swapFee,uint _tradeFee,uint _rewardFee) public{ require(msg.sender == owner); Init.updateFees(_swapFee,_tradeFee,_rewardFee); } function getOrderIds(string memory wtoken) public view returns(uint64 [] memory){ return EDM.getOrderIds(wtoken); } function fetchTokenPrice(string memory _tokenSymbol) public view returns(uint){ return EDM.fetchTokenPrice(_tokenSymbol); } function Withdraw(string memory to, uint _amount) external { address payable msgSender = msg.sender; string memory from = EMM.getWrapped(to); require(!Init.isUserLocked(msgSender), "Your Address is Locked Pay Dues"); if(EDM.getUserBorrowed(msgSender) >0 ) { require(isWithdrawEligible(msgSender, to, _amount) , "Not Eligible for Withdraw"); } wERC20 wToken = wERC20(EMM.getwTokenAddress(to)); uint amountLeft; uint availableBalance = wToken.balanceOf(msgSender) - EDM.getUserDepositsbyToken(msgSender, from) - EDM.getUserBorrowedOrderbyToken(msgSender, from); if(availableBalance >= _amount) { EMM.burnWrappedFrom(msgSender, _amount, from); EMM.WithdrawManager(to, _amount, msgSender); } else { if(keccak256(abi.encodePacked(to)) == keccak256(abi.encodePacked(Init.ECO()))) { require( wToken.balanceOf(msgSender) + EDM.getECOEarnings(msgSender) >= _amount,"Insufficient Balance"); if(wToken.balanceOf(msgSender) >=_amount) { _withdraw(msgSender, from, _amount, to); } else { amountLeft = _amount - wToken.balanceOf(msgSender); if(wToken.balanceOf(msgSender) > 0){ _withdraw(msgSender, from, wToken.balanceOf(msgSender), to); } EMM.redeemEcoEarning(msgSender,amountLeft); } } else { require(wToken.balanceOf(msgSender)>=_amount,"Insufficient balance"); _withdraw(msgSender, from, _amount, to); } } Init.emitSwap(msgSender,from,to,_amount); } function _withdraw(address payable msgSender, string memory from, uint amount, string memory to) internal { EMM.releaseWrappedToken(msgSender,amount, from); EMM.burnWrappedFrom(msgSender, amount, from); Init.setOwnerFeeVault(to,(amount*Init.rewardFee())/100); uint ecoEarnings = EDM.freePopper(msgSender,from,amount, true); if(ecoEarnings>0) { if(ecoEarnings > EMM.ecoWithdrawls(msgSender)) { ecoEarnings-=EMM.ecoWithdrawls(msgSender); if(EMM.ecoWithdrawls(msgSender) > 0) { EMM.adjustEcoEarning(msgSender, EMM.ecoWithdrawls(msgSender)); } EMM.mintECO(msgSender, ecoEarnings); } else { EMM.adjustEcoEarning(msgSender, ecoEarnings); } } uint newAmount = amount - (amount*Init.rewardFee())/100; EMM.WithdrawManager(to,newAmount, msgSender); } function isWithdrawEligible(address userAddress, string memory to, uint amount) internal view returns (bool Eligible){ return (EDM.getbuyPower(userAddress) > (amount*fetchTokenPrice(to)/(10**8))); } } contract EcoceliumInit is Initializable { address payable owner; address payable public MONEYMANAGER; address payable public DATAMANAGER; address payable public ECOCELIUM; address payable public ABACUS; string public WRAP_ECO_SYMBOL; string public ECO; string public ETH_SYMBOL; string public WRAP_ETH_SYMBOL; uint public swapFee; uint public rewardFee; uint public tradeFee; uint public CDSpercent; string [] rtokenlist; string [] wtokenlist; mapping (string => uint) public rcurrencyID; mapping (string => uint) public wcurrencyID; mapping (address => bool) public isRegistrar; mapping (address => bool) public isUserLocked; mapping (string => uint ) public ownerFeeVault; mapping (string => uint) public slabRateDeposit; mapping (address => bool) public friendlyaddress; mapping (address => address) public SponsorAddress; mapping (address => uint) public usertreasuryearnings; event OrderCreated( address userAddress, uint duration, uint yield, uint amount, string token ); event Swap( address userAddress, string from, string to, uint amount ); event Borrowed( uint64 orderId, address borrower, uint amount, uint duration ); event Deposit( address userAddress, string token, uint tokenAmount, uint collateralValue ); event DuePaid( uint64 orderId, address borrower, uint amount ); event WrapTokenCreated( address TokenAddress, string TokenName, string TokenSymbol, uint Decimals ); receive() payable external { } function initializeAddress(address payable _owner) public initializer { friendlyaddress[_owner] = true; owner = _owner; } function addRealCurrency(string memory rtoken) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); if(rcurrencyID[rtoken] == 0) { rtokenlist.push(rtoken); rcurrencyID[rtoken] = rtokenlist.length; } } function addWrapCurrency (string memory wtoken) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); if(wcurrencyID[wtoken] == 0) { wtokenlist.push(wtoken); wcurrencyID[wtoken] = wtokenlist.length; } } function setSlabRate(string memory WToken, uint rate) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); slabRateDeposit[WToken] = rate; } function setUserLocked(address userAddress, bool value) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); isUserLocked[userAddress] = value; } function setFriendlyAddress(address Address) public { (msg.sender == owner,"not owner"); friendlyaddress[Address] = true; } function addRegistrar(address _registrar) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); isRegistrar[_registrar] = true; } function setOwnerFeeVault(string memory add,uint value) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); ownerFeeVault[add] += value; } function emitOrderCreated(address userAddress, uint _duration, uint _yield, uint newAmount,string memory _tokenSymbol) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit OrderCreated(userAddress,_duration,_yield,newAmount,_tokenSymbol); } function emitSwap(address msgSender, string memory from, string memory to,uint _amount) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Swap(msgSender,from,to,_amount); } function emitBorrowed(uint64 _orderId, address msgSender, uint _amount,uint _duration) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Borrowed(_orderId,msgSender,_amount,_duration); } function emitWrappedCreated(address tokenAddress,string memory name, string memory symbol,uint8 decimals) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit WrapTokenCreated(tokenAddress,name,symbol,decimals); } function emitDeposit(address msgSender, string memory _tokenSymbol, uint amount, uint tokenUsdValue) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit Deposit(msgSender,_tokenSymbol,amount,tokenUsdValue); } function emitDuePaid(uint64 _orderId, address msgSender, uint due) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); emit DuePaid(_orderId,msgSender,due); } function setCONSTSYMBOLS(string[4] memory _symbolCONST) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); WRAP_ECO_SYMBOL = _symbolCONST[0]; ECO = _symbolCONST[1]; ETH_SYMBOL = _symbolCONST[2]; WRAP_ETH_SYMBOL = _symbolCONST[3]; } function updateFees(uint _swapFee,uint _tradeFee,uint _rewardFee) public{ require(friendlyaddress[msg.sender],"Not Friendly Address"); (swapFee,tradeFee,rewardFee) = (_swapFee,_tradeFee,_rewardFee); } function setCSDpercent(uint percent) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); CDSpercent = percent; } function changeAbacusaddress(address payable Abacusaddress) public{ require(msg.sender == owner,"not owner"); ABACUS = Abacusaddress; } function changeEcoceliumaddress(address payable Ecocelium) public{ require(msg.sender == owner,"not owner"); ECOCELIUM = Ecocelium; } function changeDMaddress(address payable DMAddress) public{ require(msg.sender == owner,"not owner"); DATAMANAGER = DMAddress; } function changeMMaddress(address payable MMaddress) public{ require(msg.sender == owner,"not owner"); MONEYMANAGER = MMaddress; } function changeOwner(address payable _owner) public{ require(msg.sender==owner); owner = _owner; } function setSponsor(address userAddress, address _sponsorAddress) external { require(friendlyaddress[msg.sender],"Not Friendly Address"); SponsorAddress[userAddress] = _sponsorAddress; } function updateTreasuryEarnings(address userAddress, uint _amount) public { require(friendlyaddress[msg.sender],"Not Friendly Address"); usertreasuryearnings[userAddress] = _amount; } } contract EcoMoneyManager is Initializable { EcoceliumInit Init; address public owner; address [] public TokenAddresses; address [] public wTokenAddresses; mapping (string => address) rTokens; mapping (string => string) rTokensTowToken; mapping (string => TokenConfig) wTokens; mapping (address => uint) public ecoWithdrawls; mapping (string => uint) public WGains; mapping (string => uint) public WLoss; receive() payable external { } struct TokenConfig{ address tokenAddress; uint64 fetchId; } function initialize(address _owner, address payable _Init) public initializer{ owner = _owner; Init = EcoceliumInit(_Init); } function updateAdminAddress(address adminAddress) public { require(msg.sender == owner); for(uint i = 0;i<wTokenAddresses.length;i++){ wERC20(wTokenAddresses[i]).changeAdmin(adminAddress); } } function addTokenWithAddress(address tokenAddress) public { require(msg.sender == owner); ERC20Basic token = ERC20Basic(tokenAddress); require(getrTokenAddress(token.symbol())== address(0),"token exist"); rTokens[token.symbol()] = tokenAddress; TokenAddresses.push(tokenAddress); } function createWrapToken(string memory name,string memory symbol,uint64 _fetchId, uint8 decimal, string memory wrapOf) public returns(address TokenAddress){ require(msg.sender == owner); wERC20 token = new wERC20(name,symbol,decimal, address(this), address(this)); rTokensTowToken[wrapOf] = symbol; TokenAddresses.push(address(token)); wTokenAddresses.push(address(token)); wTokens[symbol] = TokenConfig({ tokenAddress:address(token), fetchId : _fetchId }); Init.emitWrappedCreated(address(token),name,symbol,token.decimals()); return address(token); } function changeOwner(address _owner) public{ require(owner == msg.sender); owner =_owner; } function getwTokenAddress(string memory symbol) public view returns(address){ return wTokens[symbol].tokenAddress; } function getFetchId(string memory symbol ) public view returns(uint64){ if( wTokens[symbol].tokenAddress == address(0)) { symbol = rTokensTowToken[symbol]; } return wTokens[symbol].fetchId; } function getrTokenAddress(string memory symbol) public view returns(address){ return rTokens[symbol]; } function getTokenAddresses() public view returns(address[] memory){ return TokenAddresses; } function getWrapped(string memory symbol) public view returns(string memory){ return rTokensTowToken[symbol]; } function getTokenID(string memory symbol) public view returns(uint){ for(uint i=0; i< TokenAddresses.length; i++) { if(TokenAddresses[i] == wTokens[symbol].tokenAddress) { return i; } } } function releaseWrappedToken (address _userAddress, uint amount, string memory WToken) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(WToken)).release(_userAddress,amount); } function mintWrappedToken (address _userAddress, uint amount, string memory WToken) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(WToken)).mint(_userAddress,amount); } function lockWrappedToken (address _userAddress, uint amount, string memory WToken) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(WToken)).lock(_userAddress,amount); } function burnWrappedFrom(address userAddress, uint amount, string memory WToken) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(WToken)).burnFrom(userAddress,amount); } function mintECO(address userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(Init.WRAP_ECO_SYMBOL())).mint(userAddress,amount); } function lockECO(address userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(Init.WRAP_ECO_SYMBOL())).lock(userAddress,amount); } function releaseECO(address userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(Init.WRAP_ECO_SYMBOL())).release(userAddress,amount); } function burnECOFrom(address userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); wERC20(getwTokenAddress(Init.WRAP_ECO_SYMBOL())).burnFrom(userAddress,amount); } function DepositManager(string memory _rtoken, uint amount, address userAddress) public payable { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); if(Init.rcurrencyID(_rtoken) == Init.rcurrencyID(Init.ETH_SYMBOL())) { require(msg.value >= amount,"Invalid Amount"); } else {ERC20Basic rtoken = ERC20Basic(getrTokenAddress(_rtoken)); require(rtoken.allowance(userAddress, address(this)) >= amount,"set allowance"); rtoken.transferFrom(userAddress,address(this),amount);} } function WithdrawManager(string memory _rtoken, uint amount, address payable userAddress) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); if(Init.rcurrencyID(_rtoken) == Init.rcurrencyID(Init.ETH_SYMBOL())) { userAddress.transfer(amount); } else { ERC20Basic rtoken = ERC20Basic(getrTokenAddress(_rtoken)); rtoken.approve(userAddress, amount); rtoken.transferFrom(address(this),userAddress,amount);} } function redeemEcoEarning(address payable userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); ecoWithdrawls[userAddress] = ecoWithdrawls[userAddress] + amount; WithdrawManager(Init.ECO(), amount, userAddress); } function adjustEcoEarning(address userAddress, uint amount) public { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); ecoWithdrawls[userAddress] = ecoWithdrawls[userAddress] - amount; } function updateFetchID (string memory wtoken, uint64 _fetchID) external { require(owner == msg.sender); wTokens[wtoken].fetchId = _fetchID; } function w2wswap (address msgSender, string memory token1, uint token1amount, uint token2amount, string memory token2) external { require(Init.friendlyaddress(msg.sender),"Not Friendly Address"); releaseWrappedToken(msgSender, token1amount, token1); burnWrappedFrom(msgSender,token1amount,token1); WGains[token1]=token1amount; mintWrappedToken(msgSender,token2amount, token2); lockWrappedToken(msgSender, token2amount, token2); WLoss[token2]=token2amount; } }
0x6080604052600436106200020b5760003560e01c80636e6164d7116200011b578063c813b1b811620000a3578063e0e872bc116200006d578063e0e872bc146200062b578063e1d6e3e91462000650578063e706a6391462000675578063ee8c24b8146200069a5762000213565b8063c813b1b81462000597578063c83aad7614620005bc578063d1b5c12c14620005e1578063d1f94af414620006065762000213565b806395a1e96211620000e557806395a1e9621462000503578063a6f9dae11462000528578063bfbae3e7146200054d578063c65c440814620005725762000213565b80636e6164d7146200047c57806385e2381c14620004a15780638c36881814620004c65780638da5cb5b14620004eb5762000213565b8063376c0454116200019f578063483eb4ed1162000169578063483eb4ed14620003f6578063485cc955146200040d5780635408b02f14620004325780636517b48314620004575762000213565b8063376c045414620003445780633ce9babf146200036957806345461628146200039d578063481343e314620003c25762000213565b806315cca55411620001e157806315cca55414620002a15780631fbfe54e14620002d557806320eb66ff14620002fa5780632a23dccf146200031f5762000213565b806302167e8a1462000218578063036c9641146200023f578063077fec3e14620002645762000213565b366200021357005b600080fd5b3480156200022557600080fd5b506200023d6200023736600462002566565b620006c1565b005b3480156200024c57600080fd5b506200023d6200025e36600462002553565b620007e2565b3480156200027157600080fd5b5062000289620002833660046200280f565b62000978565b604051620002989190620028ac565b60405180910390f35b348015620002ae57600080fd5b50620002c6620002c0366004620025e4565b620009a0565b604051620002989190620029b5565b348015620002e257600080fd5b506200023d620002f4366004620027c5565b62000a54565b3480156200030757600080fd5b5062000289620003193660046200280f565b62000abc565b3480156200032c57600080fd5b506200023d6200033e36600462002433565b62000aca565b3480156200035157600080fd5b506200023d6200036336600462002553565b62000c93565b3480156200037657600080fd5b506200038e62000388366004620025e4565b62000db2565b60405162000298919062002b17565b348015620003aa57600080fd5b506200023d620003bc36600462002459565b62000ed7565b348015620003cf57600080fd5b50620003e7620003e136600462002433565b62001024565b60405162000298919062002b0e565b6200023d620004073660046200273c565b62001036565b3480156200041a57600080fd5b506200023d6200042c36600462002487565b620013b2565b3480156200043f57600080fd5b506200023d6200045136600462002566565b6200146f565b3480156200046457600080fd5b50620003e762000476366004620025e4565b6200154e565b3480156200048957600080fd5b50620002896200049b366004620025e4565b6200156b565b348015620004ae57600080fd5b506200023d620004c036600462002433565b6200159f565b348015620004d357600080fd5b506200023d620004e536600462002553565b6200164f565b348015620004f857600080fd5b50620002896200176e565b3480156200051057600080fd5b506200023d6200052236600462002553565b6200177d565b3480156200053557600080fd5b506200023d6200054736600462002433565b62001845565b3480156200055a57600080fd5b50620002896200056c3660046200269d565b6200187f565b3480156200057f57600080fd5b506200023d6200059136600462002566565b62001afe565b348015620005a457600080fd5b506200023d620005b636600462002566565b62001bdd565b348015620005c957600080fd5b50620003e7620005db366004620025e4565b62001cbc565b348015620005ee57600080fd5b506200023d6200060036600462002553565b62001cd9565b3480156200061357600080fd5b506200023d620006253660046200279a565b62001df8565b3480156200063857600080fd5b50620002896200064a366004620025e4565b6200210d565b3480156200065d57600080fd5b506200023d6200066f366004620024c4565b62002121565b3480156200068257600080fd5b50620003e762000694366004620025e4565b62002247565b348015620006a757600080fd5b50620006b2620022c6565b60405162000298919062002966565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620006f3903390600401620028ac565b60206040518083038186803b1580156200070c57600080fd5b505afa15801562000721573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620007479190620025c2565b6200076f5760405162461bcd60e51b8152600401620007669062002ae0565b60405180910390fd5b6200077a816200210d565b6001600160a01b03166340c10f1984846040518363ffffffff1660e01b8152600401620007a9929190620028e4565b600060405180830381600087803b158015620007c457600080fd5b505af1158015620007d9573d6000803e3d6000fd5b50505050505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000814903390600401620028ac565b60206040518083038186803b1580156200082d57600080fd5b505afa15801562000842573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620008689190620025c2565b620008875760405162461bcd60e51b8152600401620007669062002ae0565b6033546040805160016238880b60e11b03198152905162000911926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620008d257600080fd5b505afa158015620008e7573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200064a919081019062002622565b6001600160a01b031663282d3fdf83836040518363ffffffff1660e01b815260040162000940929190620028e4565b600060405180830381600087803b1580156200095b57600080fd5b505af115801562000970573d6000803e3d6000fd5b505050505050565b603681815481106200098657fe5b6000918252602090912001546001600160a01b0316905081565b6060603882604051620009b491906200288e565b9081526040805160209281900383018120805460026001821615610100026000190190911604601f8101859004850283018501909352828252909290919083018282801562000a475780601f1062000a1b5761010080835404028352916020019162000a47565b820191906000526020600020905b81548152906001019060200180831162000a2957829003601f168201915b505050505090505b919050565b6034546001600160a01b0316331462000a6c57600080fd5b8060398360405162000a7f91906200288e565b90815260405190819003602001902080546001600160401b0392909216600160a01b0267ffffffffffffffff60a01b199092169190911790555050565b603581815481106200098657fe5b6034546001600160a01b0316331462000ae257600080fd5b600081905060006001600160a01b031662000b6f826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801562000b3057600080fd5b505afa15801562000b45573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526200049b919081019062002622565b6001600160a01b03161462000b985760405162461bcd60e51b8152600401620007669062002a1e565b816037826001600160a01b03166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801562000bd557600080fd5b505afa15801562000bea573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262000c14919081019062002622565b60405162000c2391906200288e565b90815260405190819003602001902080546001600160a01b039283166001600160a01b031991821617909155603580546001810182556000919091527fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180549490921693169290921790915550565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000cc5903390600401620028ac565b60206040518083038186803b15801562000cde57600080fd5b505afa15801562000cf3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000d199190620025c2565b62000d385760405162461bcd60e51b8152600401620007669062002ae0565b6033546040805160016238880b60e11b03198152905162000d83926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620008d257600080fd5b6001600160a01b0316630357371d83836040518363ffffffff1660e01b815260040162000940929190620028e4565b6000806001600160a01b031660398360405162000dd091906200288e565b908152604051908190036020019020546001600160a01b0316141562000e9d5760388260405162000e0291906200288e565b9081526040805160209281900383018120805460026001821615610100026000190190911604601f8101859004850283018501909352828252909290919083018282801562000e955780601f1062000e695761010080835404028352916020019162000e95565b820191906000526020600020905b81548152906001019060200180831162000e7757829003601f168201915b505050505091505b60398260405162000eaf91906200288e565b908152604051908190036020019020546001600160401b03600160a01b909104169050919050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062000f09903390600401620028ac565b60206040518083038186803b15801562000f2257600080fd5b505afa15801562000f37573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062000f5d9190620025c2565b62000f7c5760405162461bcd60e51b8152600401620007669062002ae0565b6001600160a01b038083166000908152603a6020526040808220805485019055603354815163059f833760e41b81529151620010209491909116926359f833709260048082019391829003018186803b15801562000fd957600080fd5b505afa15801562000fee573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262001018919081019062002622565b828462001df8565b5050565b603a6020526000908152604090205481565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001068903390600401620028ac565b60206040518083038186803b1580156200108157600080fd5b505afa15801562001096573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620010bc9190620025c2565b620010db5760405162461bcd60e51b8152600401620007669062002ae0565b6033546040805163dbe3a38160e01b815290516001600160a01b039092169163a3c5cbc591839163dbe3a38191600480820192600092909190829003018186803b1580156200112957600080fd5b505afa1580156200113e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262001168919081019062002622565b6040518263ffffffff1660e01b8152600401620011869190620029b5565b60206040518083038186803b1580156200119f57600080fd5b505afa158015620011b4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620011da919062002828565b60335460405163a3c5cbc560e01b81526001600160a01b039091169063a3c5cbc5906200120c908790600401620029b5565b60206040518083038186803b1580156200122557600080fd5b505afa1580156200123a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001260919062002828565b14156200129057813410156200128a5760405162461bcd60e51b8152600401620007669062002a43565b620013ad565b60006200129d846200156b565b905082816001600160a01b031663dd62ed3e84306040518363ffffffff1660e01b8152600401620012d0929190620028fd565b60206040518083038186803b158015620012e957600080fd5b505afa158015620012fe573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001324919062002828565b1015620013455760405162461bcd60e51b8152600401620007669062002a6b565b6040516323b872dd60e01b81526001600160a01b038216906323b872dd906200137790859030908890600401620028c0565b600060405180830381600087803b1580156200139257600080fd5b505af1158015620013a7573d6000803e3d6000fd5b50505050505b505050565b600054610100900460ff1680620013ce5750620013ce6200232a565b80620013dd575060005460ff16155b620013fc5760405162461bcd60e51b8152600401620007669062002a92565b600054610100900460ff1615801562001428576000805460ff1961ff0019909116610100171660011790555b603480546001600160a01b038086166001600160a01b03199283161790925560338054928516929091169190911790558015620013ad576000805461ff0019169055505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620014a1903390600401620028ac565b60206040518083038186803b158015620014ba57600080fd5b505afa158015620014cf573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620014f59190620025c2565b620015145760405162461bcd60e51b8152600401620007669062002ae0565b6200151f816200210d565b6001600160a01b031663282d3fdf84846040518363ffffffff1660e01b8152600401620007a9929190620028e4565b8051602081830181018051603c8252928201919093012091525481565b60006037826040516200157f91906200288e565b908152604051908190036020019020546001600160a01b03169050919050565b6034546001600160a01b03163314620015b757600080fd5b60005b603654811015620010205760368181548110620015d357fe5b6000918252602090912001546040516308f2839760e41b81526001600160a01b0390911690638f283970906200160e908590600401620028ac565b600060405180830381600087803b1580156200162957600080fd5b505af11580156200163e573d6000803e3d6000fd5b505060019092019150620015ba9050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001681903390600401620028ac565b60206040518083038186803b1580156200169a57600080fd5b505afa158015620016af573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620016d59190620025c2565b620016f45760405162461bcd60e51b8152600401620007669062002ae0565b6033546040805160016238880b60e11b0319815290516200173f926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620008d257600080fd5b6001600160a01b03166379cc679083836040518363ffffffff1660e01b815260040162000940929190620028e4565b6034546001600160a01b031681565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef90620017af903390600401620028ac565b60206040518083038186803b158015620017c857600080fd5b505afa158015620017dd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620018039190620025c2565b620018225760405162461bcd60e51b8152600401620007669062002ae0565b6001600160a01b039091166000908152603a602052604090208054919091039055565b6034546001600160a01b031633146200185d57600080fd5b603480546001600160a01b0319166001600160a01b0392909216919091179055565b6034546000906001600160a01b031633146200189a57600080fd5b60008686853030604051620018af9062002330565b620018bf959493929190620029ca565b604051809103906000f080158015620018dc573d6000803e3d6000fd5b50905085603884604051620018f291906200288e565b90815260200160405180910390209080519060200190620019159291906200233e565b506035805460018181019092557fcfa4bec1d3298408bb5afcfcd9c430549c5b31f8aa5c5848151c0a55f473c34d0180546001600160a01b0384166001600160a01b031991821681179092556036805493840181556000527f4a11f94e20a93c79f6ec743a1954ec4fc2c08429ae2122118bf234b2185c81b8909201805490921681179091556040805180820182529182526001600160401b038716602083015251603990620019c79089906200288e565b908152604080516020928190038301812084518154958501516001600160a01b03199096166001600160a01b039182161767ffffffffffffffff60a01b1916600160a01b6001600160401b039097169690960295909517905560335463313ce56760e01b82529151918416936330ceb8129386938d938d9386169263313ce56792600480840193829003018186803b15801562001a6357600080fd5b505afa15801562001a78573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001a9e919062002841565b6040518563ffffffff1660e01b815260040162001abf949392919062002917565b600060405180830381600087803b15801562001ada57600080fd5b505af115801562001aef573d6000803e3d6000fd5b50929998505050505050505050565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001b30903390600401620028ac565b60206040518083038186803b15801562001b4957600080fd5b505afa15801562001b5e573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001b849190620025c2565b62001ba35760405162461bcd60e51b8152600401620007669062002ae0565b62001bae816200210d565b6001600160a01b03166379cc679084846040518363ffffffff1660e01b8152600401620007a9929190620028e4565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001c0f903390600401620028ac565b60206040518083038186803b15801562001c2857600080fd5b505afa15801562001c3d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001c639190620025c2565b62001c825760405162461bcd60e51b8152600401620007669062002ae0565b62001c8d816200210d565b6001600160a01b0316630357371d84846040518363ffffffff1660e01b8152600401620007a9929190620028e4565b8051602081830181018051603b8252928201919093012091525481565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001d0b903390600401620028ac565b60206040518083038186803b15801562001d2457600080fd5b505afa15801562001d39573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001d5f9190620025c2565b62001d7e5760405162461bcd60e51b8152600401620007669062002ae0565b6033546040805160016238880b60e11b03198152905162001dc9926001600160a01b03169163ff8eefea916004808301926000929190829003018186803b158015620008d257600080fd5b6001600160a01b03166340c10f1983836040518363ffffffff1660e01b815260040162000940929190620028e4565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062001e2a903390600401620028ac565b60206040518083038186803b15801562001e4357600080fd5b505afa15801562001e58573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001e7e9190620025c2565b62001e9d5760405162461bcd60e51b8152600401620007669062002ae0565b6033546040805163dbe3a38160e01b815290516001600160a01b039092169163a3c5cbc591839163dbe3a38191600480820192600092909190829003018186803b15801562001eeb57600080fd5b505afa15801562001f00573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405262001f2a919081019062002622565b6040518263ffffffff1660e01b815260040162001f489190620029b5565b60206040518083038186803b15801562001f6157600080fd5b505afa15801562001f76573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062001f9c919062002828565b60335460405163a3c5cbc560e01b81526001600160a01b039091169063a3c5cbc59062001fce908790600401620029b5565b60206040518083038186803b15801562001fe757600080fd5b505afa15801562001ffc573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019062002022919062002828565b141562002067576040516001600160a01b0382169083156108fc029084906000818181858888f1935050505015801562002060573d6000803e3d6000fd5b50620013ad565b600062002074846200156b565b60405163095ea7b360e01b81529091506001600160a01b0382169063095ea7b390620020a79085908790600401620028e4565b600060405180830381600087803b158015620020c257600080fd5b505af1158015620020d7573d6000803e3d6000fd5b50506040516323b872dd60e01b81526001600160a01b03841692506323b872dd91506200137790309086908890600401620028c0565b60006039826040516200157f91906200288e565b603354604051632f3c2fef60e01b81526001600160a01b0390911690632f3c2fef9062002153903390600401620028ac565b60206040518083038186803b1580156200216c57600080fd5b505afa15801562002181573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620021a79190620025c2565b620021c65760405162461bcd60e51b8152600401620007669062002ae0565b620021d385848662001bdd565b620021e085848662001afe565b82603b85604051620021f391906200288e565b9081526040519081900360200190205562002210858383620006c1565b6200221d8583836200146f565b81603c826040516200223091906200288e565b908152604051908190036020019020555050505050565b6000805b603554811015620022c0576039836040516200226891906200288e565b90815260405190819003602001902054603580546001600160a01b0390921691839081106200229357fe5b6000918252602090912001546001600160a01b03161415620022b757905062000a4f565b6001016200224b565b50919050565b606060358054806020026020016040519081016040528092919081815260200182805480156200232057602002820191906000526020600020905b81546001600160a01b0316815260019091019060200180831162002301575b5050505050905090565b303b1590565b6123b78062002be983390190565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200238157805160ff1916838001178555620023b1565b82800160010185558215620023b1579182015b82811115620023b157825182559160200191906001019062002394565b50620023bf929150620023c3565b5090565b5b80821115620023bf5760008155600101620023c4565b600082601f830112620023eb578081fd5b813562002402620023fc8262002b52565b62002b2b565b91508082528360208285010111156200241a57600080fd5b8060208401602084013760009082016020015292915050565b60006020828403121562002445578081fd5b8135620024528162002ba9565b9392505050565b600080604083850312156200246c578081fd5b8235620024798162002ba9565b946020939093013593505050565b600080604083850312156200249a578182fd5b8235620024a78162002ba9565b91506020830135620024b98162002ba9565b809150509250929050565b600080600080600060a08688031215620024dc578081fd5b8535620024e98162002ba9565b945060208601356001600160401b038082111562002505578283fd5b6200251389838a01620023da565b95506040880135945060608801359350608088013591508082111562002537578283fd5b506200254688828901620023da565b9150509295509295909350565b600080604083850312156200246c578182fd5b6000806000606084860312156200257b578283fd5b8335620025888162002ba9565b92506020840135915060408401356001600160401b03811115620025aa578182fd5b620025b886828701620023da565b9150509250925092565b600060208284031215620025d4578081fd5b8151801515811462002452578182fd5b600060208284031215620025f6578081fd5b81356001600160401b038111156200260c578182fd5b6200261a84828501620023da565b949350505050565b60006020828403121562002634578081fd5b81516001600160401b038111156200264a578182fd5b8201601f810184136200265b578182fd5b80516200266c620023fc8262002b52565b81815285602083850101111562002681578384fd5b6200269482602083016020860162002b76565b95945050505050565b600080600080600060a08688031215620026b5578081fd5b85356001600160401b0380821115620026cc578283fd5b620026da89838a01620023da565b96506020880135915080821115620026f0578283fd5b620026fe89838a01620023da565b955060408801359150620027128262002bc2565b909350606087013590620027268262002bd8565b9092506080870135908082111562002537578283fd5b60008060006060848603121562002751578283fd5b83356001600160401b0381111562002767578384fd5b6200277586828701620023da565b9350506020840135915060408401356200278f8162002ba9565b809150509250925092565b600080600060608486031215620027af578081fd5b83356001600160401b0381111562002767578182fd5b60008060408385031215620027d8578182fd5b82356001600160401b03811115620027ee578283fd5b620027fc85828601620023da565b9250506020830135620024b98162002bc2565b60006020828403121562002821578081fd5b5035919050565b6000602082840312156200283a578081fd5b5051919050565b60006020828403121562002853578081fd5b8151620024528162002bd8565b600081518084526200287a81602086016020860162002b76565b601f01601f19169290920160200192915050565b60008251620028a281846020870162002b76565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03851681526080602082018190526000906200293d9083018662002860565b828103604084015262002951818662002860565b91505060ff8316606083015295945050505050565b6020808252825182820181905260009190848201906040850190845b81811015620029a95783516001600160a01b03168352928401929184019160010162002982565b50909695505050505050565b60006020825262002452602083018462002860565b600060a08252620029df60a083018862002860565b8281036020840152620029f3818862002860565b60ff96909616604084015250506001600160a01b039283166060820152911660809091015292915050565b6020808252600b908201526a1d1bdad95b88195e1a5cdd60aa1b604082015260600190565b6020808252600e908201526d125b9d985b1a5908105b5bdd5b9d60921b604082015260600190565b6020808252600d908201526c73657420616c6c6f77616e636560981b604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b6020808252601490820152734e6f7420467269656e646c79204164647265737360601b604082015260600190565b90815260200190565b6001600160401b0391909116815260200190565b6040518181016001600160401b038111828210171562002b4a57600080fd5b604052919050565b60006001600160401b0382111562002b68578081fd5b50601f01601f191660200190565b60005b8381101562002b9357818101518382015260200162002b79565b8381111562002ba3576000848401525b50505050565b6001600160a01b038116811462002bbf57600080fd5b50565b6001600160401b038116811462002bbf57600080fd5b60ff8116811462002bbf57600080fdfe60806040523480156200001157600080fd5b50604051620023b7380380620023b7833981810160405260a08110156200003757600080fd5b81019080805160405193929190846401000000008211156200005857600080fd5b9083019060208201858111156200006e57600080fd5b82516401000000008111828201881017156200008957600080fd5b82525081516020918201929091019080838360005b83811015620000b85781810151838201526020016200009e565b50505050905090810190601f168015620000e65780820380516001836020036101000a031916815260200191505b50604052602001805160405193929190846401000000008211156200010a57600080fd5b9083019060208201858111156200012057600080fd5b82516401000000008111828201881017156200013b57600080fd5b82525081516020918201929091019080838360005b838110156200016a57818101518382015260200162000150565b50505050905090810190601f168015620001985780820380516001836020036101000a031916815260200191505b506040908152602082810151918301516060909301518751929550929350869186918691620001ce9160059190860190620003b1565b508151620001e4906006906020850190620003b1565b506007805460ff191660ff929092169190911761ff0019169055506200020e90506000836200029d565b6200023a7fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d654826200029d565b620002667f9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6836200029d565b620002927f65d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a836200029d565b50505050506200044d565b620002a98282620002ad565b5050565b600082815260208181526040909120620002d291839062000e3f62000326821b17901c565b15620002a957620002e262000346565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60006200033d836001600160a01b0384166200034a565b90505b92915050565b3390565b600062000358838362000399565b620003905750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915562000340565b50600062000340565b60009081526001919091016020526040902054151590565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620003f457805160ff191683800117855562000424565b8280016001018555821562000424579182015b828111156200042457825182559160200191906001019062000407565b506200043292915062000436565b5090565b5b8082111562000432576000815560010162000437565b611f5a806200045d6000396000f3fe608060405234801561001057600080fd5b50600436106101f05760003560e01c806379cc67901161010f578063a457c2d7116100a2578063d547741f11610071578063d547741f1461061b578063dd62ed3e14610647578063e10f67ca14610675578063e63ab1e91461067d576101f0565b8063a457c2d71461059e578063a9059cbb146105ca578063ca15c873146105f6578063d539139314610613576101f0565b806391d14854116100de57806391d148541461053c57806395d89b4114610568578063a153e70814610570578063a217fddf14610596576101f0565b806379cc6790146104a35780638456cb59146104cf5780638f283970146104d75780639010d07c146104fd576101f0565b8063313ce5671161018757806340c10f191161015657806340c10f19146104235780635c975abb1461044f578063654259dd1461045757806370a082311461047d576101f0565b8063313ce567146103a557806336568abe146103c357806339509351146103ef5780633f4ba83a1461041b576101f0565b806323b872dd116101c357806323b872dd146102fa578063248a9ca314610330578063282d3fdf1461034d5780632f2ff15d14610379576101f0565b80630357371d146101f557806306fdde0314610223578063095ea7b3146102a057806318160ddd146102e0575b600080fd5b6102216004803603604081101561020b57600080fd5b506001600160a01b038135169060200135610685565b005b61022b6106ed565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561026557818101518382015260200161024d565b50505050905090810190601f1680156102925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102cc600480360360408110156102b657600080fd5b506001600160a01b038135169060200135610783565b604080519115158252519081900360200190f35b6102e86107a1565b60408051918252519081900360200190f35b6102cc6004803603606081101561031057600080fd5b506001600160a01b038135811691602081013590911690604001356107a7565b6102e86004803603602081101561034657600080fd5b503561082e565b6102216004803603604081101561036357600080fd5b506001600160a01b038135169060200135610843565b6102216004803603604081101561038f57600080fd5b50803590602001356001600160a01b03166108a2565b6103ad610905565b6040805160ff9092168252519081900360200190f35b610221600480360360408110156103d957600080fd5b50803590602001356001600160a01b031661090e565b6102cc6004803603604081101561040557600080fd5b506001600160a01b03813516906020013561096f565b6102216109bd565b6102216004803603604081101561043957600080fd5b506001600160a01b038135169060200135610a1c565b6102cc610a7b565b6102e86004803603602081101561046d57600080fd5b50356001600160a01b0316610a89565b6102e86004803603602081101561049357600080fd5b50356001600160a01b0316610ab5565b610221600480360360408110156104b957600080fd5b506001600160a01b038135169060200135610ad0565b610221610b2f565b610221600480360360208110156104ed57600080fd5b50356001600160a01b0316610b8c565b6105206004803603604081101561051357600080fd5b5080359060200135610c31565b604080516001600160a01b039092168252519081900360200190f35b6102cc6004803603604081101561055257600080fd5b50803590602001356001600160a01b0316610c50565b61022b610c68565b6102e86004803603602081101561058657600080fd5b50356001600160a01b0316610cc9565b6102e8610cdb565b6102cc600480360360408110156105b457600080fd5b506001600160a01b038135169060200135610ce0565b6102cc600480360360408110156105e057600080fd5b506001600160a01b038135169060200135610d48565b6102e86004803603602081101561060c57600080fd5b5035610d5c565b6102e8610d73565b6102216004803603604081101561063157600080fd5b50803590602001356001600160a01b0316610d85565b6102e86004803603604081101561065d57600080fd5b506001600160a01b0381358116916020013516610dde565b6102e8610e09565b6102e8610e2d565b6106a4600080516020611ccd83398151915261069f610e54565b610c50565b6106df5760405162461bcd60e51b8152600401808060200182810382526038815260200180611eed6038913960400191505060405180910390fd5b6106e98282610e58565b5050565b60058054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156107795780601f1061074e57610100808354040283529160200191610779565b820191906000526020600020905b81548152906001019060200180831161075c57829003601f168201915b5050505050905090565b6000610797610790610e54565b8484610f4d565b5060015b92915050565b60045490565b60006107b4848484611080565b610824846107c0610e54565b61081f85604051806060016040528060288152602001611c4f602891396001600160a01b038a166000908152600360205260408120906107fe610e54565b6001600160a01b031681526020810191909152604001600020549190611224565b610f4d565b5060019392505050565b60009081526020819052604090206002015490565b61085d600080516020611ccd83398151915261069f610e54565b6108985760405162461bcd60e51b8152600401808060200182810382526035815260200180611de26035913960400191505060405180910390fd5b6106e982826112bb565b6000828152602081905260409020600201546108c09061069f610e54565b6108fb5760405162461bcd60e51b815260040180806020018281038252602f815260200180611ac5602f913960400191505060405180910390fd5b6106e98282611380565b60075460ff1690565b610916610e54565b6001600160a01b0316816001600160a01b0316146109655760405162461bcd60e51b815260040180806020018281038252602f815260200180611e94602f913960400191505060405180910390fd5b6106e982826113e9565b600061079761097c610e54565b8461081f856003600061098d610e54565b6001600160a01b03908116825260208083019390935260409182016000908120918c168152925290205490611452565b6109d7600080516020611c7783398151915261069f610e54565b610a125760405162461bcd60e51b8152600401808060200182810382526039815260200180611b166039913960400191505060405180910390fd5b610a1a6114ac565b565b610a36600080516020611ccd83398151915261069f610e54565b610a715760405162461bcd60e51b8152600401808060200182810382526036815260200180611c976036913960400191505060405180910390fd5b6106e98282611550565b600754610100900460ff1690565b6001600160a01b03811660009081526002602052604081205461079b90610aaf84610ab5565b90611642565b6001600160a01b031660009081526001602052604090205490565b610aea600080516020611ccd83398151915261069f610e54565b610b255760405162461bcd60e51b8152600401808060200182810382526035815260200180611bc36035913960400191505060405180910390fd5b6106e98282611684565b610b49600080516020611c7783398151915261069f610e54565b610b845760405162461bcd60e51b8152600401808060200182810382526037815260200180611dab6037913960400191505060405180910390fd5b610a1a6117c7565b610bb87fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d65461069f610e54565b610bf35760405162461bcd60e51b815260040180806020018281038252602d815260200180611e67602d913960400191505060405180910390fd5b610bfe6000826108fb565b610c16600080516020611ccd833981519152826108fb565b610c2e600080516020611c77833981519152826108fb565b50565b6000828152602081905260408120610c49908361184f565b9392505050565b6000828152602081905260408120610c49908361185b565b60068054604080516020601f60026000196101006001881615020190951694909404938401819004810282018101909252828152606093909290918301828280156107795780601f1061074e57610100808354040283529160200191610779565b60026020526000908152604090205481565b600081565b6000610797610ced610e54565b8461081f85604051806060016040528060258152602001611e426025913960036000610d17610e54565b6001600160a01b03908116825260208083019390935260409182016000908120918d16815292529020549190611224565b6000610797610d55610e54565b8484611080565b600081815260208190526040812061079b90611870565b600080516020611ccd83398151915281565b600082815260208190526040902060020154610da39061069f610e54565b6109655760405162461bcd60e51b8152600401808060200182810382526030815260200180611bf86030913960400191505060405180910390fd5b6001600160a01b03918216600090815260036020908152604080832093909416825291909152205490565b7fde00661a9bee31b253f6d0c9cfdafe0b25df2574c0f3debb8203f6dcff62d65481565b600080516020611c7783398151915281565b6000610c49836001600160a01b03841661187b565b3390565b6001600160a01b038216610eb3576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a2072656c6561736520666f72207a65726f206164647265737300604482015290519081900360640190fd5b6001600160a01b038216600090815260026020526040902054811115610f0a5760405162461bcd60e51b815260040180806020018281038252602c815260200180611b71602c913960400191505060405180910390fd5b6001600160a01b038216600090815260026020526040902054610f2d9082611642565b6001600160a01b0390921660009081526002602052604090209190915550565b6001600160a01b038316610f925760405162461bcd60e51b8152600401808060200182810382526024815260200180611d586024913960400191505060405180910390fd5b6001600160a01b038216610fd75760405162461bcd60e51b8152600401808060200182810382526022815260200180611b4f6022913960400191505060405180910390fd5b610fe083610a89565b81111561101e5760405162461bcd60e51b815260040180806020018281038252602f815260200180611d7c602f913960400191505060405180910390fd5b6001600160a01b03808416600081815260036020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b0383166110c55760405162461bcd60e51b8152600401808060200182810382526025815260200180611d336025913960400191505060405180910390fd5b6001600160a01b03821661110a5760405162461bcd60e51b8152600401808060200182810382526023815260200180611aa26023913960400191505060405180910390fd5b61111383610a89565b8111156111515760405162461bcd60e51b8152600401808060200182810382526027815260200180611c286027913960400191505060405180910390fd5b61115c8383836118c5565b61119981604051806060016040528060268152602001611b9d602691396001600160a01b0386166000908152600160205260409020549190611224565b6001600160a01b0380851660009081526001602052604080822093909355908416815220546111c89082611452565b6001600160a01b0380841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600081848411156112b35760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015611278578181015183820152602001611260565b50505050905090810190601f1680156112a55780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b6001600160a01b038216611316576040805162461bcd60e51b815260206004820152601c60248201527f45524332303a206c6f636b20666f72207a65726f206164647265737300000000604482015290519081900360640190fd5b61131f82610a89565b81111561135d5760405162461bcd60e51b815260040180806020018281038252602b815260200180611e17602b913960400191505060405180910390fd5b6001600160a01b038216600090815260026020526040902054610f2d9082611452565b60008281526020819052604090206113989082610e3f565b156106e9576113a5610e54565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b600082815260208190526040902061140190826118d5565b156106e95761140e610e54565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b600082820183811015610c49576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b600754610100900460ff166114ff576040805162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b604482015290519081900360640190fd5b6007805461ff00191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa611533610e54565b604080516001600160a01b039092168252519081900360200190a1565b6001600160a01b0382166115ab576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b6115b7600083836118c5565b6004546115c49082611452565b6004556001600160a01b0382166000908152600160205260409020546115ea9082611452565b6001600160a01b03831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6000610c4983836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250611224565b6001600160a01b0382166116c95760405162461bcd60e51b8152600401808060200182810382526021815260200180611d126021913960400191505060405180910390fd5b6116d282610a89565b8111156117105760405162461bcd60e51b8152600401808060200182810382526025815260200180611ced6025913960400191505060405180910390fd5b61171c826000836118c5565b61175981604051806060016040528060228152602001611af4602291396001600160a01b0385166000908152600160205260409020549190611224565b6001600160a01b03831660009081526001602052604090205560045461177f9082611642565b6004556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b600754610100900460ff1615611817576040805162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b604482015290519081900360640190fd5b6007805461ff0019166101001790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258611533610e54565b6000610c4983836118ea565b6000610c49836001600160a01b03841661194e565b600061079b82611966565b6000611887838361194e565b6118bd5750815460018181018455600084815260208082209093018490558454848252828601909352604090209190915561079b565b50600061079b565b6118d083838361196a565b505050565b6000610c49836001600160a01b0384166119b9565b8154600090821061192c5760405162461bcd60e51b8152600401808060200182810382526022815260200180611a806022913960400191505060405180910390fd5b82600001828154811061193b57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b5490565b6119758383836118d0565b61197d610a7b565b156118d05760405162461bcd60e51b815260040180806020018281038252602a815260200180611ec3602a913960400191505060405180910390fd5b60008181526001830160205260408120548015611a7557835460001980830191908101906000908790839081106119ec57fe5b9060005260206000200154905080876000018481548110611a0957fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080611a3957fe5b6001900381819060005260206000200160009055905586600101600087815260200190815260200160002060009055600194505050505061079b565b600091505061079b56fe456e756d657261626c655365743a20696e646578206f7574206f6620626f756e647345524332303a207472616e7366657220746f20746865207a65726f2061646472657373416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f206772616e7445524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20756e706175736545524332303a20617070726f766520746f20746865207a65726f20616464726573734552433230203a2072656c656173652076616c7565206d6f7265207468656e206c6f636b65642076616c756545524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f206275726e416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e2061646d696e20746f207265766f6b654552433230203a20616d6f756e74206578636565647320617661696c61626c6520616d6f756e7445524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636565d7a28e3265b37a6474929f336521b332c1681b933f6cb9f3376673440d862a45524332305072657365744d696e7465725061757365723a206d7573742068617665206d696e74657220726f6c6520746f206d696e749f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a64552433230203a206275726e206578636565647320617661696c61626c6520616d6f756e7445524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573734552433230203a20617070726f766520616d6f756e74206578636565647320617661696c61626c6520616d6f756e7445524332305072657365744d696e7465725061757365723a206d75737420686176652070617573657220726f6c6520746f20706175736545524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f206c6f636b45524332303a206c6f636b2076616c7565206d6f72652074686120617661696c61626c6520616d6f756e7445524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f45524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c65416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636520726f6c657320666f722073656c6645524332305061757361626c653a20746f6b656e207472616e73666572207768696c652070617573656445524332305072657365744d696e7465725061757365723a206d75737420686176652061646d696e20726f6c6520746f2072656c65617365a264697066735822122043e50b954e8de778aad15e090b5e91d9521cb66a65083bff85dee41855e2e95164736f6c634300060c0033a26469706673582212200a2f91f2b958f9bffd0f45f826c66b75cc32d5adb49bd51ea3dfdbced9e9d0dc64736f6c634300060c0033
[ 4, 7, 17, 11, 9, 12, 13, 5, 2 ]
0x5c6d81d0a2245efe11aebc352dcdd5dd53ea0879
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; struct ProtocolBalance { ProtocolMetadata metadata; AdapterBalance[] adapterBalances; } struct ProtocolMetadata { string name; string description; string websiteURL; string iconURL; uint256 version; } struct AdapterBalance { AdapterMetadata metadata; FullTokenBalance[] balances; } struct AdapterMetadata { address adapterAddress; string adapterType; // "Asset", "Debt" } struct FullTokenBalance { TokenBalance base; TokenBalance[] underlying; } struct TokenBalance { TokenMetadata metadata; uint256 amount; } struct TokenMetadata { address token; string name; string symbol; uint8 decimals; } struct Component { address token; string tokenType; // "ERC20" by default uint256 rate; // price per full share (1e18) } interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); 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) external view returns (uint256); } interface TokenAdapter { /** * @dev MUST return TokenMetadata struct with ERC20-style token info. * struct TokenMetadata { * address token; * string name; * string symbol; * uint8 decimals; * } */ function getMetadata(address token) external view returns (TokenMetadata memory); /** * @dev MUST return array of Component structs with underlying tokens rates for the given token. * struct Component { * address token; // Address of token contract * string tokenType; // Token type ("ERC20" by default) * uint256 rate; // Price per share (1e18) * } */ function getComponents(address token) external view returns (Component[] memory); } contract CompoundRegistry { mapping(address => address) internal cTokens; constructor() public { cTokens[0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359] = 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC; cTokens[0x1985365e9f78359a9B6AD760e32412f4a445E862] = 0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1; cTokens[0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE] = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; cTokens[0x6B175474E89094C44Da98b954EedeAC495271d0F] = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; cTokens[0x0D8775F648430679A709E98d2b0Cb6250d2887EF] = 0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E; cTokens[0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599] = 0xC11b1268C1A384e55C48c2391d8d480264A3A7F4; cTokens[0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48] = 0x39AA39c021dfbaE8faC545936693aC917d5E7563; cTokens[0xE41d2489571d322189246DaFA5ebDe1F4699F498] = 0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407; cTokens[0xdAC17F958D2ee523a2206206994597C13D831ec7] = 0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9; } function getCToken(address token) external view returns (address) { return cTokens[token]; } } interface CToken { function exchangeRateStored() external view returns (uint256); function underlying() external view returns (address); } contract CompoundTokenAdapter is TokenAdapter { address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address internal constant CETH = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address internal constant CRETH = 0xD06527D5e56A3495252A528C4987003b712860eE; address internal constant CSAI = 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC; /** * @return TokenMetadata struct with ERC20-style token info. * @dev Implementation of TokenAdapter interface function. */ function getMetadata(address token) external view override returns (TokenMetadata memory) { if (token == CSAI) { return TokenMetadata({ token: CSAI, name: "Compound Sai", symbol: "cSAI", decimals: uint8(8) }); } else { return TokenMetadata({ token: token, name: ERC20(token).name(), symbol: ERC20(token).symbol(), decimals: ERC20(token).decimals() }); } } /** * @return Array of Component structs with underlying tokens rates for the given token. * @dev Implementation of TokenAdapter interface function. */ function getComponents(address token) external view override returns (Component[] memory) { Component[] memory underlyingTokens = new Component[](1); underlyingTokens[0] = Component({ token: getUnderlying(token), tokenType: "ERC20", rate: CToken(token).exchangeRateStored() }); return underlyingTokens; } /** * @dev Internal function to retrieve underlying token. */ function getUnderlying(address token) internal view returns (address) { if (token == CETH || token == CRETH) { return ETH; } else { return CToken(token).underlying(); } } }
0x608060405234801561001057600080fd5b50600436106100365760003560e01c80632a50c1461461003b57806379b1833414610064575b600080fd5b61004e61004936600461063a565b610084565b60405161005b9190610867565b60405180910390f35b61007761007236600461063a565b61037a565b60405161005b91906107b5565b61008c6105c2565b73ffffffffffffffffffffffffffffffffffffffff821673f5dce57282a584d2746faf1593d3121fcac444dc141561017e57604051806080016040528073f5dce57282a584d2746faf1593d3121fcac444dc73ffffffffffffffffffffffffffffffffffffffff1681526020016040518060400160405280600c81526020017f436f6d706f756e6420536169000000000000000000000000000000000000000081525081526020016040518060400160405280600481526020017f63534149000000000000000000000000000000000000000000000000000000008152508152602001600860ff168152509050610375565b60405180608001604052808373ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff166306fdde036040518163ffffffff1660e01b815260040160006040518083038186803b1580156101eb57600080fd5b505afa1580156101ff573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526102459190810190610679565b81526020018373ffffffffffffffffffffffffffffffffffffffff166395d89b416040518163ffffffff1660e01b815260040160006040518083038186803b15801561029057600080fd5b505afa1580156102a4573d6000803e3d6000fd5b505050506040513d6000823e601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01682016040526102ea9190810190610679565b81526020018373ffffffffffffffffffffffffffffffffffffffff1663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561033557600080fd5b505afa158015610349573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061036d919061074a565b60ff16905290505b919050565b604080516001808252818301909252606091829190816020015b61039c610603565b81526020019060019003908161039457905050905060405180606001604052806103c5856104ba565b73ffffffffffffffffffffffffffffffffffffffff1681526020016040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081526020018473ffffffffffffffffffffffffffffffffffffffff1663182df0f56040518163ffffffff1660e01b815260040160206040518083038186803b15801561046157600080fd5b505afa158015610475573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104999190610732565b815250816000815181106104a957fe5b602090810291909101015292915050565b600073ffffffffffffffffffffffffffffffffffffffff8216734ddc2d193948926d02f9b1fe9e1daa0718270ed5148061051d575073ffffffffffffffffffffffffffffffffffffffff821673d06527d5e56a3495252a528c4987003b712860ee145b1561053d575073eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee610375565b8173ffffffffffffffffffffffffffffffffffffffff16636f307dc36040518163ffffffff1660e01b815260040160206040518083038186803b15801561058357600080fd5b505afa158015610597573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105bb919061065d565b9050610375565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff1681526020016060815260200160608152602001600060ff1681525090565b6040518060600160405280600073ffffffffffffffffffffffffffffffffffffffff16815260200160608152602001600081525090565b60006020828403121561064b578081fd5b813561065681610927565b9392505050565b60006020828403121561066e578081fd5b815161065681610927565b60006020828403121561068a578081fd5b815167ffffffffffffffff808211156106a1578283fd5b81840185601f8201126106b2578384fd5b80519250818311156106c2578384fd5b60405160207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8601168201018181108482111715610700578586fd5b604052838152818401602001871015610717578485fd5b6107288460208301602085016108f7565b9695505050505050565b600060208284031215610743578081fd5b5051919050565b60006020828403121561075b578081fd5b815160ff81168114610656578182fd5b600081518084526107838160208601602086016108f7565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b60208082528251828201819052600091906040908185019080840286018301878501865b83811015610859577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08984030185528151606073ffffffffffffffffffffffffffffffffffffffff825116855288820151818a87015261083b8287018261076b565b928901519589019590955250948701949250908601906001016107d9565b509098975050505050505050565b60006020825273ffffffffffffffffffffffffffffffffffffffff83511660208301526020830151608060408401526108a360a084018261076b565b604085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08482030160608501526108de818361076b565b60ff606087015116608086015280935050505092915050565b60005b838110156109125781810151838201526020016108fa565b83811115610921576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff8116811461094957600080fd5b5056fea2646970667358221220b539f6cd1e9960a7e886c1fedece0d75ef88fd40463056435c447517af76c31f64736f6c63430006050033
[ 38 ]
0x5d1Ecff2eF5919d14C47bF7474D1AfDd71077A2c
pragma solidity 0.5.17; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract VEGA is ERC20, ERC20Detailed { constructor(uint256 initialSupply) ERC20Detailed("VEGA", "VEGA", 18) public { _mint(msg.sender, initialSupply); } }
0x608060405234801561001057600080fd5b50600436106100a95760003560e01c80633950935111610071578063395093511461025f57806370a08231146102c557806395d89b411461031d578063a457c2d7146103a0578063a9059cbb14610406578063dd62ed3e1461046c576100a9565b806306fdde03146100ae578063095ea7b31461013157806318160ddd1461019757806323b872dd146101b5578063313ce5671461023b575b600080fd5b6100b66104e4565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156100f65780820151818401526020810190506100db565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61017d6004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610586565b604051808215151515815260200191505060405180910390f35b61019f6105a4565b6040518082815260200191505060405180910390f35b610221600480360360608110156101cb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105ae565b604051808215151515815260200191505060405180910390f35b610243610687565b604051808260ff1660ff16815260200191505060405180910390f35b6102ab6004803603604081101561027557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061069e565b604051808215151515815260200191505060405180910390f35b610307600480360360208110156102db57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610751565b6040518082815260200191505060405180910390f35b610325610799565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561036557808201518184015260208101905061034a565b50505050905090810190601f1680156103925780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6103ec600480360360408110156103b657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061083b565b604051808215151515815260200191505060405180910390f35b6104526004803603604081101561041c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610908565b604051808215151515815260200191505060405180910390f35b6104ce6004803603604081101561048257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610926565b6040518082815260200191505060405180910390f35b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561057c5780601f106105515761010080835404028352916020019161057c565b820191906000526020600020905b81548152906001019060200180831161055f57829003601f168201915b5050505050905090565b600061059a6105936109ad565b84846109b5565b6001905092915050565b6000600254905090565b60006105bb848484610bac565b61067c846105c76109ad565b6106778560405180606001604052806028815260200161101660289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600061062d6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e629092919063ffffffff16565b6109b5565b600190509392505050565b6000600560009054906101000a900460ff16905090565b60006107476106ab6109ad565b8461074285600160006106bc6109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2290919063ffffffff16565b6109b5565b6001905092915050565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108315780601f1061080657610100808354040283529160200191610831565b820191906000526020600020905b81548152906001019060200180831161081457829003601f168201915b5050505050905090565b60006108fe6108486109ad565b846108f98560405180606001604052806025815260200161108760259139600160006108726109ad565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e629092919063ffffffff16565b6109b5565b6001905092915050565b600061091c6109156109ad565b8484610bac565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a3b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806110636024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ac1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526022815260200180610fce6022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c32576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061103e6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610cb8576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180610fab6023913960400191505060405180910390fd5b610d2381604051806060016040528060268152602001610ff0602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610e629092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610db6816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054610f2290919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290610f0f576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610ed4578082015181840152602081019050610eb9565b50505050905090810190601f168015610f015780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015610fa0576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b809150509291505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e636545524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a72315820ad257d8fcfaf3a025705b4307f24b9e4e5fad3eab00c8c4c6edfb15dcab15f0464736f6c63430005110032
[ 38 ]
0x5d77f9b5a4cca418f2cd62b6e1cf0ba123d4c05f
pragma solidity 0.5.7; 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 Mints `amount` tokens to address `account`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function mint(address account, 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); } 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 subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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; } } library SafeMath64 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a, "SafeMath: subtraction overflow"); uint64 c = a - b; return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint64 a, uint64 b, string memory errorMessage) internal pure returns (uint64) { require(b <= a, errorMessage); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // 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; } uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint64 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(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } contract Staking { using SafeMath for uint256; /** * @dev Structure to store Interest details. * It contains total amount of tokens staked and globalYield. */ struct InterestData { uint256 globalTotalStaked; uint256 globalYieldPerToken; uint256 lastUpdated; mapping(address => Staker) stakers; } /** * @dev Structure to store staking details. * It contains amount of tokens staked and withdrawn interest. */ struct Staker { uint256 totalStaked; uint256 withdrawnToDate; uint256 stakeBuyinRate; } // Token address ERC20 private stakeToken; // Reward token PlotXToken private rewardToken; // Interest and staker data InterestData public interestData; uint public stakingStartTime; uint public totalReward; // unclaimed reward will be trasfered to this account address public vaultAddress; // 10^18 uint256 private constant DECIMAL1e18 = 10**18; //Total time (in sec) over which reward will be distributed uint256 public stakingPeriod; /** * @dev Emitted when `staker` stake `value` tokens. */ event Staked(address indexed staker, uint256 value, uint256 _globalYieldPerToken); /** * @dev Emitted when `staker` withdraws their stake `value` tokens. */ event StakeWithdrawn(address indexed staker, uint256 value, uint256 _globalYieldPerToken); /** * @dev Emitted when `staker` collects interest `_value`. */ event InterestCollected( address indexed staker, uint256 _value, uint256 _globalYieldPerToken ); /** * @dev Constructor * @param _stakeToken The address of stake Token * @param _rewardToken The address of reward Token * @param _stakingPeriod valid staking time after staking starts * @param _totalRewardToBeDistributed total amount to be distributed as reward */ constructor( address _stakeToken, address _rewardToken, uint256 _stakingPeriod, uint256 _totalRewardToBeDistributed, uint256 _stakingStart, address _vaultAdd ) public { require(_stakingPeriod > 0, "Should be positive"); require(_totalRewardToBeDistributed > 0, "Total reward can not be 0"); require(_stakingStart >= now, "Can not be past time"); require(_stakeToken != address(0), "Can not be null address"); require(_rewardToken != address(0), "Can not be null address"); require(_vaultAdd != address(0), "Can not be null address"); stakeToken = ERC20(_stakeToken); rewardToken = PlotXToken(_rewardToken); stakingStartTime = _stakingStart; interestData.lastUpdated = _stakingStart; stakingPeriod = _stakingPeriod; totalReward = _totalRewardToBeDistributed; vaultAddress = _vaultAdd; } /** * @dev Allows a staker to deposit Tokens. Notice that `approve` is * needed to be executed before the execution of this method. * @param _amount The amount of tokens to stake */ function stake(uint256 _amount) external { require(_amount > 0, "You need to stake a positive token amount"); require( stakeToken.transferFrom(msg.sender, address(this), _amount), "TransferFrom failed, make sure you approved token transfer" ); require(now.sub(stakingStartTime) <= stakingPeriod, "Can not stake after staking period passed"); uint newlyInterestGenerated = now.sub(interestData.lastUpdated).mul(totalReward).div(stakingPeriod); interestData.lastUpdated = now; updateGlobalYieldPerToken(newlyInterestGenerated); updateStakeData(msg.sender, _amount); emit Staked(msg.sender, _amount, interestData.globalYieldPerToken); } /** * @dev Updates InterestData and Staker data while staking. * must call update globalYieldPerToken before this operation * @param _staker Staker's address * @param _stake Amount of stake * */ function updateStakeData( address _staker, uint256 _stake ) internal { Staker storage _stakerData = interestData.stakers[_staker]; _stakerData.totalStaked = _stakerData.totalStaked.add(_stake); updateStakeBuyinRate( _stakerData, interestData.globalYieldPerToken, _stake ); interestData.globalTotalStaked = interestData.globalTotalStaked.add(_stake); } /** * @dev Calculates and updates the yield rate in which the staker has entered * a staker may stake multiple times, so we calculate his cumulative rate his earning will be calculated based on GlobalYield and StakeBuyinRate * Formula: * StakeBuyinRate = [StakeBuyinRate(P) + (GlobalYield(P) x Stake)] * * @param _stakerData Staker's Data * @param _globalYieldPerToken Total yielding amount per token * @param _stake Amount staked * */ function updateStakeBuyinRate( Staker storage _stakerData, uint256 _globalYieldPerToken, uint256 _stake ) internal { _stakerData.stakeBuyinRate = _stakerData.stakeBuyinRate.add( _globalYieldPerToken.mul(_stake).div(DECIMAL1e18) ); } /** * @dev Withdraws the sender staked Token. */ function withdrawStakeAndInterest(uint256 _amount) external { Staker storage staker = interestData.stakers[msg.sender]; require(_amount > 0, "Should withdraw positive amount"); require(staker.totalStaked >= _amount, "Not enough token staked"); withdrawInterest(); updateStakeAndInterestData(msg.sender, _amount); require(stakeToken.transfer(msg.sender, _amount), "withdraw transfer failed"); emit StakeWithdrawn(msg.sender, _amount, interestData.globalYieldPerToken); } /** * @dev Updates InterestData and Staker data while withdrawing stake. * * @param _staker Staker address * @param _amount Amount of stake to withdraw * */ function updateStakeAndInterestData( address _staker, uint256 _amount ) internal { Staker storage _stakerData = interestData.stakers[_staker]; _stakerData.totalStaked = _stakerData.totalStaked.sub(_amount); interestData.globalTotalStaked = interestData.globalTotalStaked.sub(_amount); _stakerData.stakeBuyinRate = 0; _stakerData.withdrawnToDate = 0; updateStakeBuyinRate( _stakerData, interestData.globalYieldPerToken, _stakerData.totalStaked ); } /** * @dev Withdraws the sender Earned interest. */ function withdrawInterest() public { uint timeSinceLastUpdate = _timeSinceLastUpdate(); uint newlyInterestGenerated = timeSinceLastUpdate.mul(totalReward).div(stakingPeriod); updateGlobalYieldPerToken(newlyInterestGenerated); uint256 interest = calculateInterest(msg.sender); Staker storage stakerData = interestData.stakers[msg.sender]; stakerData.withdrawnToDate = stakerData.withdrawnToDate.add(interest); require(rewardToken.transfer(msg.sender, interest), "Withdraw interest transfer failed"); emit InterestCollected(msg.sender, interest, interestData.globalYieldPerToken); } function updateGlobalYield() public { uint timeSinceLastUpdate = _timeSinceLastUpdate(); uint newlyInterestGenerated = timeSinceLastUpdate.mul(totalReward).div(stakingPeriod); updateGlobalYieldPerToken(newlyInterestGenerated); } function getYieldData(address _staker) public view returns(uint256, uint256) { return (interestData.globalYieldPerToken, interestData.stakers[_staker].stakeBuyinRate); } function _timeSinceLastUpdate() internal returns(uint256) { uint timeSinceLastUpdate; if(now.sub(stakingStartTime) > stakingPeriod) { timeSinceLastUpdate = stakingStartTime.add(stakingPeriod).sub(interestData.lastUpdated); interestData.lastUpdated = stakingStartTime.add(stakingPeriod); } else { timeSinceLastUpdate = now.sub(interestData.lastUpdated); interestData.lastUpdated = now; } return timeSinceLastUpdate; } /** * @dev Calculates Interest for staker for their stake. * * Formula: * EarnedInterest = MAX[TotalStaked x GlobalYield - (StakeBuyinRate + WithdrawnToDate), 0] * * @param _staker Staker's address * * @return The amount of tokens credit for the staker. */ function calculateInterest(address _staker) public view returns (uint256) { Staker storage stakerData = interestData.stakers[_staker]; uint256 _withdrawnToDate = stakerData.withdrawnToDate; uint256 intermediateInterest = stakerData .totalStaked .mul(interestData.globalYieldPerToken).div(DECIMAL1e18); uint256 intermediateVal = _withdrawnToDate.add( stakerData.stakeBuyinRate ); // will lead to -ve value if (intermediateVal > intermediateInterest) { return 0; } uint _earnedInterest = (intermediateInterest.sub(intermediateVal)); return _earnedInterest; } /** * @dev Calculates and updates new accrued amount per token since last update. * * Formula: * GlobalYield = GlobalYield(P) + newlyGeneratedInterest/GlobalTotalStake. * * @param _interestGenerated Interest token earned since last update. * */ function updateGlobalYieldPerToken( uint256 _interestGenerated ) internal { if (interestData.globalTotalStaked == 0) { require(rewardToken.transfer(vaultAddress, _interestGenerated), "Transfer failed while trasfering to vault"); return; } interestData.globalYieldPerToken = interestData.globalYieldPerToken.add( _interestGenerated .mul(DECIMAL1e18) .div(interestData.globalTotalStaked) ); } function getStakerData(address _staker) public view returns(uint256, uint256) { return (interestData.stakers[_staker].totalStaked, interestData.stakers[_staker].withdrawnToDate); } /** * @dev returns stats data. * @param _staker Address of staker. * @return Total staked. * @return Total reward to be distributed. * @return estimated reward for user at end of staking period if no one stakes from current time. * @return Unlocked reward based on elapsed time. * @return Accrued reward for user till now. */ function getStatsData(address _staker) external view returns(uint, uint, uint, uint, uint) { Staker storage stakerData = interestData.stakers[_staker]; uint estimatedReward = 0; uint unlockedReward = 0; uint accruedReward = 0; uint timeElapsed = now.sub(stakingStartTime); if(timeElapsed > stakingPeriod) { timeElapsed = stakingPeriod; } unlockedReward = timeElapsed.mul(totalReward).div(stakingPeriod); uint timeSinceLastUpdate; if(timeElapsed == stakingPeriod) { timeSinceLastUpdate = stakingStartTime.add(stakingPeriod).sub(interestData.lastUpdated); } else { timeSinceLastUpdate = now.sub(interestData.lastUpdated); } uint newlyInterestGenerated = timeSinceLastUpdate.mul(totalReward).div(stakingPeriod); uint updatedGlobalYield; uint stakingTimeLeft = 0; if(now < stakingStartTime.add(stakingPeriod)){ stakingTimeLeft = stakingStartTime.add(stakingPeriod).sub(now); } uint interestGeneratedEnd = stakingTimeLeft.mul(totalReward).div(stakingPeriod); uint globalYieldEnd; if (interestData.globalTotalStaked != 0) { updatedGlobalYield = interestData.globalYieldPerToken.add( newlyInterestGenerated .mul(DECIMAL1e18) .div(interestData.globalTotalStaked)); globalYieldEnd = updatedGlobalYield.add(interestGeneratedEnd.mul(DECIMAL1e18).div(interestData.globalTotalStaked)); } accruedReward = stakerData .totalStaked .mul(updatedGlobalYield).div(DECIMAL1e18); if (stakerData.withdrawnToDate.add(stakerData.stakeBuyinRate) > accruedReward) { accruedReward = 0; } else { accruedReward = accruedReward.sub(stakerData.withdrawnToDate.add(stakerData.stakeBuyinRate)); } estimatedReward = stakerData .totalStaked .mul(globalYieldEnd).div(DECIMAL1e18); if (stakerData.withdrawnToDate.add(stakerData.stakeBuyinRate) > estimatedReward) { estimatedReward = 0; } else { estimatedReward = estimatedReward.sub(stakerData.withdrawnToDate.add(stakerData.stakeBuyinRate)); } return (interestData.globalTotalStaked, totalReward, estimatedReward, unlockedReward, accruedReward); } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @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 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 Moves tokens `amount` from `sender` to `recipient`. * * 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) internal { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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)); } } contract PlotXToken is ERC20 { using SafeMath for uint256; mapping(address => uint256) public lockedForGV; string public name = "PLOT"; string public symbol = "PLOT"; uint8 public decimals = 18; address public operator; modifier onlyOperator() { require(msg.sender == operator, "Not operator"); _; } /** * @dev Initialize PLOT token * @param _initialSupply Initial token supply * @param _initialTokenHolder Initial token holder address */ constructor(uint256 _initialSupply, address _initialTokenHolder) public { _mint(_initialTokenHolder, _initialSupply); operator = _initialTokenHolder; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { require(_newOperator != address(0), "New operator cannot be 0 address"); operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public { _burn(msg.sender, amount); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The address which you want to send tokens from * @param value uint256 The amount of token to be burned */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator returns (bool) { _mint(account, amount); return true; } /** * @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(lockedForGV[msg.sender] < now, "Locked for governance"); // if not voted under governance _transfer(msg.sender, to, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom( address from, address to, uint256 value ) public returns (bool) { require(lockedForGV[from] < now, "Locked for governance"); // if not voted under governance _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForGovernanceVote(address _of, uint256 _period) public onlyOperator { if (_period.add(now) > lockedForGV[_of]) lockedForGV[_of] = _period.add(now); } function isLockedForGV(address _of) public view returns (bool) { return (lockedForGV[_of] > now); } }
0x608060405234801561001057600080fd5b50600436106100ce5760003560e01c8063750142e61161008c578063c03d5b4711610066578063c03d5b47146101ca578063c601f352146101d2578063e11932cf146101f8578063ebbbabbd1461021e576100ce565b8063750142e6146101665780637943913d1461016e578063a694fc3a146101ad576100ce565b806263750c146100d357806304c3a8a3146100dd57806329c257a2146100fa5780633b71be5914610102578063430bf08a146101285780636abfd1831461014c575b600080fd5b6100db61026f565b005b6100db600480360360208110156100f357600080fd5b50356103ef565b6100db6105d9565b61010a610611565b60408051938452602084019290925282820152519081900360600190f35b61013061061d565b604080516001600160a01b039092168252519081900360200190f35b61015461062c565b60408051918252519081900360200190f35b610154610632565b6101946004803603602081101561018457600080fd5b50356001600160a01b0316610638565b6040805192835260208301919091528051918290030190f35b6100db600480360360208110156101c357600080fd5b503561065c565b61015461084a565b610194600480360360208110156101e857600080fd5b50356001600160a01b0316610850565b6101546004803603602081101561020e57600080fd5b50356001600160a01b0316610873565b6102446004803603602081101561023457600080fd5b50356001600160a01b0316610906565b6040805195865260208601949094528484019290925260608401526080830152519081900360a00190f35b6000610279610bd2565b905060006102a460095461029860075485610c5290919063ffffffff16565b9063ffffffff610cb716565b90506102af81610d24565b60006102ba33610873565b3360009081526005602052604090206001810154919250906102e2908363ffffffff610e2016565b6001808301919091555460408051600160e01b63a9059cbb0281523360048201526024810185905290516001600160a01b039092169163a9059cbb916044808201926020929091908290030181600087803b15801561034057600080fd5b505af1158015610354573d6000803e3d6000fd5b505050506040513d602081101561036a57600080fd5b50516103aa57604051600160e51b62461bcd0281526004018080602001828103825260218152602001806110846021913960400191505060405180910390fd5b600354604080518481526020810192909252805133927f9bbd517758fbae61197f1c1c04c8614064e89512dbaf4350dcdf76fcaa5e216192908290030190a250505050565b336000908152600560205260409020816104535760408051600160e51b62461bcd02815260206004820152601f60248201527f53686f756c6420776974686472617720706f73697469766520616d6f756e7400604482015290519081900360640190fd5b80548211156104ac5760408051600160e51b62461bcd02815260206004820152601760248201527f4e6f7420656e6f75676820746f6b656e207374616b6564000000000000000000604482015290519081900360640190fd5b6104b461026f565b6104be3383610e7d565b6000805460408051600160e01b63a9059cbb0281523360048201526024810186905290516001600160a01b039092169263a9059cbb926044808401936020939083900390910190829087803b15801561051657600080fd5b505af115801561052a573d6000803e3d6000fd5b505050506040513d602081101561054057600080fd5b50516105965760408051600160e51b62461bcd02815260206004820152601860248201527f7769746864726177207472616e73666572206661696c65640000000000000000604482015290519081900360640190fd5b600354604080518481526020810192909252805133927f933735aa8de6d7547d0126171b2f31b9c34dd00f3ecd4be85a0ba047db4fafef92908290030190a25050565b60006105e3610bd2565b9050600061060260095461029860075485610c5290919063ffffffff16565b905061060d81610d24565b5050565b60025460035460045483565b6008546001600160a01b031681565b60065481565b60075481565b6003546001600160a01b038216600090815260056020526040902060020154915091565b6000811161069e57604051600160e51b62461bcd028152600401808060200182810382526029815260200180610fd76029913960400191505060405180910390fd5b6000805460408051600160e01b6323b872dd0281523360048201523060248201526044810185905290516001600160a01b03909216926323b872dd926064808401936020939083900390910190829087803b1580156106fc57600080fd5b505af1158015610710573d6000803e3d6000fd5b505050506040513d602081101561072657600080fd5b505161076657604051600160e51b62461bcd02815260040180806020018281038252603a815260200180611000603a913960400191505060405180910390fd5b60095460065461077d90429063ffffffff610ee316565b11156107bd57604051600160e51b62461bcd02815260040180806020018281038252602981526020018061103a6029913960400191505060405180910390fd5b60006107ee6009546102986007546107e2600280015442610ee390919063ffffffff16565b9063ffffffff610c5216565b4260045590506107fd81610d24565b6108073383610f43565b600354604080518481526020810192909252805133927f1449c6dd7851abc30abf37f57715f492010519147cc2652fbc38202c18a6ee9092908290030190a25050565b60095481565b6001600160a01b0316600090815260056020526040902080546001909101549091565b6001600160a01b03811660009081526005602052604081206001810154600354825484916108b591670de0b6b3a764000091610298919063ffffffff610c5216565b905060006108d0846002015484610e2090919063ffffffff16565b9050818111156108e7576000945050505050610901565b60006108f9838363ffffffff610ee316565b955050505050505b919050565b6001600160a01b03811660009081526005602052604081206006548291829182918291829081908190819061094290429063ffffffff610ee316565b905060095481111561095357506009545b61096e60095461029860075484610c5290919063ffffffff16565b925060006009548214156109ad576004546009546006546109a6929161099a919063ffffffff610e2016565b9063ffffffff610ee316565b90506109c4565b6004546109c190429063ffffffff610ee316565b90505b60006109e160095461029860075485610c5290919063ffffffff16565b60095460065491925060009182916109ff919063ffffffff610e2016565b421015610a2457610a214261099a600954600654610e2090919063ffffffff16565b90505b6000610a4160095461029860075485610c5290919063ffffffff16565b60025490915060009015610ab757600254610a8190610a729061029888670de0b6b3a764000063ffffffff610c5216565b6003549063ffffffff610e2016565b600254909450610ab490610aa79061029885670de0b6b3a764000063ffffffff610c5216565b859063ffffffff610e2016565b90505b8a54610ad790670de0b6b3a764000090610298908763ffffffff610c5216565b975087610af58c600201548d60010154610e2090919063ffffffff16565b1115610b045760009750610b32565b610b2f610b228c600201548d60010154610e2090919063ffffffff16565b899063ffffffff610ee316565b97505b8a54610b5290670de0b6b3a764000090610298908463ffffffff610c5216565b995089610b708c600201548d60010154610e2090919063ffffffff16565b1115610b7f5760009950610bad565b610baa610b9d8c600201548d60010154610e2090919063ffffffff16565b8b9063ffffffff610ee316565b99505b5050600254600754909e509c50969a5094985092965050505050505091939590929450565b600080600954610bed60065442610ee390919063ffffffff16565b1115610c3257600454600954600654610c11929161099a919063ffffffff610e2016565b9050610c2a600954600654610e2090919063ffffffff16565b600455610c4d565b600454610c4690429063ffffffff610ee316565b4260045590505b905090565b600082610c6157506000610cb1565b82820282848281610c6e57fe5b0414610cae57604051600160e51b62461bcd0281526004018080602001828103825260218152602001806110636021913960400191505060405180910390fd5b90505b92915050565b6000808211610d105760408051600160e51b62461bcd02815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b6000828481610d1b57fe5b04949350505050565b600254610df65760015460085460408051600160e01b63a9059cbb0281526001600160a01b039283166004820152602481018590529051919092169163a9059cbb9160448083019260209291908290030181600087803b158015610d8757600080fd5b505af1158015610d9b573d6000803e3d6000fd5b505050506040513d6020811015610db157600080fd5b5051610df157604051600160e51b62461bcd0281526004018080602001828103825260298152602001806110a56029913960400191505060405180910390fd5b610e1d565b600254610e1990610a729061029884670de0b6b3a764000063ffffffff610c5216565b6003555b50565b600082820183811015610cae5760408051600160e51b62461bcd02815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b6001600160a01b03821660009081526005602052604090208054610ea7908363ffffffff610ee316565b8155600254610ebc908363ffffffff610ee316565b6002908155600090820181905560018201556003548154610ede918391610f99565b505050565b600082821115610f3d5760408051600160e51b62461bcd02815260206004820152601e60248201527f536166654d6174683a207375627472616374696f6e206f766572666c6f770000604482015290519081900360640190fd5b50900390565b6001600160a01b03821660009081526005602052604090208054610f6d908363ffffffff610e2016565b8155600354610f7e90829084610f99565b600254610f91908363ffffffff610e2016565b600255505050565b610fc9610fb8670de0b6b3a7640000610298858563ffffffff610c5216565b60028501549063ffffffff610e2016565b836002018190555050505056fe596f75206e65656420746f207374616b65206120706f73697469766520746f6b656e20616d6f756e745472616e7366657246726f6d206661696c65642c206d616b65207375726520796f7520617070726f76656420746f6b656e207472616e7366657243616e206e6f74207374616b65206166746572207374616b696e6720706572696f6420706173736564536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77576974686472617720696e746572657374207472616e73666572206661696c65645472616e73666572206661696c6564207768696c652074726173666572696e6720746f207661756c74a165627a7a72305820cd2c829af5130d3d8b5c8aa18a0da733a676bfba645b67b8462a93e9491a9d730029
[ 12, 4, 9, 7 ]
0x5d929AA919E489505CcAAd8A199619c6DCA0c2de
pragma solidity 0.5.4; contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; newOwner = address(0); } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyNewOwner() { require(msg.sender != address(0)); require(msg.sender == newOwner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); newOwner = _newOwner; } function acceptOwnership() public onlyNewOwner returns(bool) { emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function allowance(address owner, address spender) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } contract BaaSid is ERC20, Ownable, Pausable { using SafeMath for uint256; struct LockupInfo { uint256 releaseTime; uint256 lockupBalance; } string public name; string public symbol; uint8 constant public decimals =18; uint256 internal initialSupply; uint256 internal totalSupply_; uint256 internal mintCap; mapping(address => uint256) internal balances; mapping(address => bool) internal locks; mapping(address => bool) public frozen; mapping(address => mapping(address => uint256)) internal allowed; mapping(address => LockupInfo[]) internal lockupInfo; address implementation; event Lock(address indexed holder, uint256 value); event Unlock(address indexed holder, uint256 value); event Burn(address indexed owner, uint256 value); event Mint(uint256 value); event Freeze(address indexed holder); event Unfreeze(address indexed holder); modifier notFrozen(address _holder) { require(!frozen[_holder]); _; } constructor() public { name = "BaaSid"; symbol = "BAAS"; initialSupply = 10000000000; totalSupply_ = initialSupply * 10 ** uint(decimals); mintCap = 10000000000 * 10 ** uint(decimals); balances[owner] = totalSupply_; emit Transfer(address(0), owner, totalSupply_); } function () payable external { address impl = implementation; require(impl != address(0)); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } function _setImplementation(address _newImp) internal { implementation = _newImp; } function upgradeTo(address _newImplementation) public onlyOwner { require(implementation != _newImplementation); _setImplementation(_newImplementation); } function totalSupply() public view returns (uint256) { return totalSupply_; } function transfer(address _to, uint256 _value) public whenNotPaused notFrozen(msg.sender) returns (bool) { if (locks[msg.sender]) { autoUnlock(msg.sender); } require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function multiTransfer(address[] memory _toList, uint256[] memory _valueList) public whenNotPaused notFrozen(msg.sender) returns(bool){ if(_toList.length != _valueList.length){ revert(); } for(uint256 i = 0; i < _toList.length; i++){ transfer(_toList[i], _valueList[i]); } return true; } function balanceOf(address _holder) public view returns (uint256 balance) { uint256 lockedBalance = 0; if(locks[_holder]) { for(uint256 idx = 0; idx < lockupInfo[_holder].length ; idx++ ) { lockedBalance = lockedBalance.add(lockupInfo[_holder][idx].lockupBalance); } } return balances[_holder] + lockedBalance; } function currentBalanceOf(address _holder) public view returns(uint256 balance){ uint256 unlockedBalance = 0; if(locks[_holder]){ for(uint256 idx =0; idx < lockupInfo[_holder].length; idx++){ if( lockupInfo[_holder][idx].releaseTime <= now){ unlockedBalance = unlockedBalance.add(lockupInfo[_holder][idx].lockupBalance); } } } return balances[_holder] + unlockedBalance; } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused notFrozen(_from)returns (bool) { if (locks[_from]) { autoUnlock(_from); } require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = (allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function decreaseAllowance( address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); allowed[msg.sender][spender] = (allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, allowed[msg.sender][spender]); return true; } function allowance(address _holder, address _spender) public view returns (uint256) { return allowed[_holder][_spender]; } function lock(address _holder, uint256 _releaseStart, uint256 _amount) public onlyOwner returns(bool){ require(balances[_holder] >= _amount); balances[_holder] = balances[_holder].sub(_amount); lockupInfo[_holder].push( LockupInfo(_releaseStart, _amount) ); locks[_holder] = true; emit Lock(_holder, _amount); return true; } function _unlock(address _holder, uint256 _idx) internal returns (bool) { require(locks[_holder]); require(_idx < lockupInfo[_holder].length); LockupInfo storage lockupinfo = lockupInfo[_holder][_idx]; uint256 releaseAmount = lockupinfo.lockupBalance; delete lockupInfo[_holder][_idx]; lockupInfo[_holder][_idx] = lockupInfo[_holder][lockupInfo[_holder].length.sub(1)]; lockupInfo[_holder].length -= 1; if(lockupInfo[_holder].length == 0){ locks[_holder] = false; } emit Unlock(_holder, releaseAmount); balances[_holder] = balances[_holder].add(releaseAmount); return true; } function unlock(address _holder, uint256 _idx) public onlyOwner returns (bool) { _unlock(_holder, _idx); } function freezeAccount(address _holder) public onlyOwner returns (bool) { require(!frozen[_holder]); frozen[_holder] = true; emit Freeze(_holder); return true; } function unfreezeAccount(address _holder) public onlyOwner returns (bool) { require(frozen[_holder]); frozen[_holder] = false; emit Unfreeze(_holder); return true; } function getNowTime() public view returns(uint256) { return now; } function showLockState(address _holder, uint256 _idx) public view returns (bool, uint256, uint256, uint256) { if(locks[_holder]) { return ( locks[_holder], lockupInfo[_holder].length, lockupInfo[_holder][_idx].releaseTime, lockupInfo[_holder][_idx].lockupBalance ); } else { return ( locks[_holder], lockupInfo[_holder].length, 0,0 ); } } function distribute(address _to, uint256 _value) public onlyOwner returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function claimToken(ERC20 token, address _to, uint256 _value) public onlyOwner returns (bool) { token.transfer(_to, _value); return true; } function burn(uint256 _value) public onlyOwner returns (bool success) { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); return true; } function burnFrom(address account, uint256 _value) public returns (bool) { uint256 decreasedAllowance = allowance(account, msg.sender).sub(_value); approve(msg.sender, decreasedAllowance); burn(_value); } function mint(address _to, uint256 _amount) onlyOwner public returns (bool) { require(mintCap >= totalSupply_.add(_amount)); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(address(0), _to, _amount); return true; } function autoUnlock(address _holder) internal returns(bool){ if(locks[_holder] == false){ return true; } for(uint256 idx = 0; idx < lockupInfo[_holder].length; idx++){ if(lockupInfo[_holder][idx].releaseTime <= now) { if(_unlock(_holder, idx)){ idx -= 1; } } } return true; } }
0x60806040526004361061020b576000357c01000000000000000000000000000000000000000000000000000000009004806379ba50971161012a578063a9059cbb116100bd578063dd62ed3e1161008c578063dd62ed3e14610dfa578063e2ab691d14610e7f578063f26c159f14610efc578063f2fde38b14610f65578063fb93210814610fb65761020b565b8063a9059cbb14610c3f578063c9e075c614610cb2578063d051665014610d3a578063d4ee1d9014610da35761020b565b80638da5cb5b116100f95780638da5cb5b14610aba57806395d89b4114610b115780639b819d3814610ba1578063a457c2d714610bcc5761020b565b806379ba50971461098e57806379cc6790146109bd5780637eee288d14610a305780638456cb5914610aa35761020b565b80633659cfe6116101a257806342966c681161017157806342966c681461083e5780635c975abb1461089157806370a08231146108c0578063788649ea146109255761020b565b80633659cfe6146106f057806339509351146107415780633f4ba83a146107b457806340c10f19146107cb5761020b565b80631e89d545116101de5780631e89d5451461045657806323b872dd146105c7578063313ce5671461065a578063353b66681461068b5761020b565b806306fdde0314610295578063095ea7b314610325578063125bfb661461039857806318160ddd1461042b575b6000600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415151561026e57600080fd5b60405136600082376000803683855af43d806000843e8160008114610291578184f35b8184fd5b3480156102a157600080fd5b506102aa611029565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156102ea5780820151818401526020810190506102cf565b50505050905090810190601f1680156103175780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561033157600080fd5b5061037e6004803603604081101561034857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506110c7565b604051808215151515815260200191505060405180910390f35b3480156103a457600080fd5b50610411600480360360608110156103bb57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506111d5565b604051808215151515815260200191505060405180910390f35b34801561043757600080fd5b5061044061131c565b6040518082815260200191505060405180910390f35b34801561046257600080fd5b506105ad6004803603604081101561047957600080fd5b810190808035906020019064010000000081111561049657600080fd5b8201836020820111156104a857600080fd5b803590602001918460208302840111640100000000831117156104ca57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561052a57600080fd5b82018360208201111561053c57600080fd5b8035906020019184602083028401116401000000008311171561055e57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050509192919290505050611326565b604051808215151515815260200191505060405180910390f35b3480156105d357600080fd5b50610640600480360360608110156105ea57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061140f565b604051808215151515815260200191505060405180910390f35b34801561066657600080fd5b5061066f6118a3565b604051808260ff1660ff16815260200191505060405180910390f35b34801561069757600080fd5b506106da600480360360208110156106ae57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506118a8565b6040518082815260200191505060405180910390f35b3480156106fc57600080fd5b5061073f6004803603602081101561071357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611a83565b005b34801561074d57600080fd5b5061079a6004803603604081101561076457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611b47565b604051808215151515815260200191505060405180910390f35b3480156107c057600080fd5b506107c9611d7e565b005b3480156107d757600080fd5b50610824600480360360408110156107ee57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611e3d565b604051808215151515815260200191505060405180910390f35b34801561084a57600080fd5b506108776004803603602081101561086157600080fd5b8101908080359060200190929190505050611fdf565b604051808215151515815260200191505060405180910390f35b34801561089d57600080fd5b506108a66121fd565b604051808215151515815260200191505060405180910390f35b3480156108cc57600080fd5b5061090f600480360360208110156108e357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612210565b6040518082815260200191505060405180910390f35b34801561093157600080fd5b506109746004803603602081101561094857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050612384565b604051808215151515815260200191505060405180910390f35b34801561099a57600080fd5b506109a36124dd565b604051808215151515815260200191505060405180910390f35b3480156109c957600080fd5b50610a16600480360360408110156109e057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506126ba565b604051808215151515815260200191505060405180910390f35b348015610a3c57600080fd5b50610a8960048036036040811015610a5357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506126f7565b604051808215151515815260200191505060405180910390f35b348015610aaf57600080fd5b50610ab8612765565b005b348015610ac657600080fd5b50610acf612824565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b348015610b1d57600080fd5b50610b26612849565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610b66578082015181840152602081019050610b4b565b50505050905090810190601f168015610b935780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b348015610bad57600080fd5b50610bb66128e7565b6040518082815260200191505060405180910390f35b348015610bd857600080fd5b50610c2560048036036040811015610bef57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506128ef565b604051808215151515815260200191505060405180910390f35b348015610c4b57600080fd5b50610c9860048036036040811015610c6257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050612b26565b604051808215151515815260200191505060405180910390f35b348015610cbe57600080fd5b50610d0b60048036036040811015610cd557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050612e1f565b604051808515151515815260200184815260200183815260200182815260200194505050505060405180910390f35b348015610d4657600080fd5b50610d8960048036036020811015610d5d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061307b565b604051808215151515815260200191505060405180910390f35b348015610daf57600080fd5b50610db861309b565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b348015610e0657600080fd5b50610e6960048036036040811015610e1d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506130c1565b6040518082815260200191505060405180910390f35b348015610e8b57600080fd5b50610ee260048036036060811015610ea257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919080359060200190929190505050613148565b604051808215151515815260200191505060405180910390f35b348015610f0857600080fd5b50610f4b60048036036020811015610f1f57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506133cf565b604051808215151515815260200191505060405180910390f35b348015610f7157600080fd5b50610fb460048036036020811015610f8857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050613529565b005b348015610fc257600080fd5b5061100f60048036036040811015610fd957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050613604565b604051808215151515815260200191505060405180910390f35b60028054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156110bf5780601f10611094576101008083540402835291602001916110bf565b820191906000526020600020905b8154815290600101906020018083116110a257829003601f168201915b505050505081565b6000600160149054906101000a900460ff161515156110e557600080fd5b81600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561123257600080fd5b8373ffffffffffffffffffffffffffffffffffffffff1663a9059cbb84846040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156112d557600080fd5b505af11580156112e9573d6000803e3d6000fd5b505050506040513d60208110156112ff57600080fd5b810190808051906020019092919050505050600190509392505050565b6000600554905090565b6000600160149054906101000a900460ff1615151561134457600080fd5b33600960008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615151561139e57600080fd5b825184511415156113ae57600080fd5b60008090505b8451811015611403576113f585828151811015156113ce57fe5b9060200190602002015185838151811015156113e657fe5b90602001906020020151612b26565b5080806001019150506113b4565b50600191505092915050565b6000600160149054906101000a900460ff1615151561142d57600080fd5b83600960008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615151561148757600080fd5b600860008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16156114e4576114e285613884565b505b600073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff161415151561152057600080fd5b600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054831115151561156e57600080fd5b600a60008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205483111515156115f957600080fd5b61164b83600760008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139cc90919063ffffffff16565b600760008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506116e083600760008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139e590919063ffffffff16565b600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506117b283600a60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139cc90919063ffffffff16565b600a60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b601281565b60008060009050600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615611a395760008090505b600b60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002080549050811015611a375742600b60008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208281548110151561199e57fe5b906000526020600020906002020160000154111515611a2a57611a27600b60008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002082815481101515611a0657fe5b906000526020600020906002020160010154836139e590919063ffffffff16565b91505b8080600101915050611907565b505b80600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401915050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515611ade57600080fd5b8073ffffffffffffffffffffffffffffffffffffffff16600c60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151515611b3b57600080fd5b611b4481613a03565b50565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515611b8457600080fd5b611c1382600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139e590919063ffffffff16565b600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515611dd957600080fd5b600160149054906101000a900460ff161515611df457600080fd5b6000600160146101000a81548160ff0219169083151502179055507f7805862f689e2f13df9f062ff482ad3ad112aca9e0847911ed832e158c525b3360405160405180910390a1565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515611e9a57600080fd5b611eaf826005546139e590919063ffffffff16565b60065410151515611ebf57600080fd5b611ed4826005546139e590919063ffffffff16565b600581905550611f2c82600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139e590919063ffffffff16565b600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561203c57600080fd5b600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054821115151561208a57600080fd5b60003390506120e183600760008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139cc90919063ffffffff16565b600760008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550612139836005546139cc90919063ffffffff16565b6005819055508073ffffffffffffffffffffffffffffffffffffffff167fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca5846040518082815260200191505060405180910390a2600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a36001915050919050565b600160149054906101000a900460ff1681565b60008060009050600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161561233a5760008090505b600b60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208054905081101561233857612329600b60008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208281548110151561230857fe5b906000526020600020906002020160010154836139e590919063ffffffff16565b9150808060010191505061226f565b505b80600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401915050919050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156123e157600080fd5b600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151561243957600080fd5b6000600960008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff167fca5069937e68fd197927055037f59d7c90bf75ac104e6e375539ef480c3ad6ee60405160405180910390a260019050919050565b60008073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415151561251a57600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561257657600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555090565b6000806126d9836126cb86336130c1565b6139cc90919063ffffffff16565b90506126e533826110c7565b506126ef83611fdf565b505092915050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561275457600080fd5b61275e8383613a47565b5092915050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156127c057600080fd5b600160149054906101000a900460ff161515156127dc57600080fd5b60018060146101000a81548160ff0219169083151502179055507f6985a02210a168e66602d3235cb6db0e70f92b3ba4d376a33c0f3d9434bff62560405160405180910390a1565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60038054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156128df5780601f106128b4576101008083540402835291602001916128df565b820191906000526020600020905b8154815290600101906020018083116128c257829003601f168201915b505050505081565b600042905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415151561292c57600080fd5b6129bb82600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139cc90919063ffffffff16565b600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600a60003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000600160149054906101000a900460ff16151515612b4457600080fd5b33600960008273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151515612b9e57600080fd5b600860003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615612bfb57612bf933613884565b505b600073ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff1614151515612c3757600080fd5b600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548311151515612c8557600080fd5b612cd783600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139cc90919063ffffffff16565b600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550612d6c83600760008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139e590919063ffffffff16565b600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a3600191505092915050565b600080600080600860008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615612fd057600860008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16600b60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002080549050600b60008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002087815481101515612f5357fe5b906000526020600020906002020160000154600b60008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002088815481101515612fb157fe5b9060005260206000209060020201600101549350935093509350613072565b600860008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16600b60008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208054905060008081915080905093509350935093505b92959194509250565b60096020528060005260406000206000915054906101000a900460ff1681565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600a60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156131a557600080fd5b81600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054101515156131f357600080fd5b61324582600760008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139cc90919063ffffffff16565b600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600b60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206040805190810160405280858152602001848152509080600181540180825580915050906001820390600052602060002090600202016000909192909190915060008201518160000155602082015181600101555050506001600860008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508373ffffffffffffffffffffffffffffffffffffffff167f625fed9875dada8643f2418b838ae0bc78d9a148a18eee4ee1979ff0f3f5d427836040518082815260200191505060405180910390a2600190509392505050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561342c57600080fd5b600960008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff1615151561348557600080fd5b6001600960008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055508173ffffffffffffffffffffffffffffffffffffffff167faf85b60d26151edd11443b704d424da6c43d0468f2235ebae3d1904dbc32304960405160405180910390a260019050919050565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561358457600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141515156135c057600080fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561366157600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415151561369d57600080fd5b600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482111515156136eb57600080fd5b61373d82600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139cc90919063ffffffff16565b600760003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506137d282600760008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139e590919063ffffffff16565b600760008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000801515600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151514156138e757600190506139c7565b60008090505b600b60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020805490508110156139c15742600b60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208281548110151561398457fe5b9060005260206000209060020201600001541115156139b4576139a78382613a47565b156139b3576001810390505b5b80806001019150506138ed565b50600190505b919050565b60008282111515156139da57fe5b818303905092915050565b60008082840190508381101515156139f957fe5b8091505092915050565b80600c60006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6000600860008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff161515613aa157600080fd5b600b60008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208054905082101515613af157600080fd5b6000600b60008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002083815481101515613b3f57fe5b90600052602060002090600202019050600081600101549050600b60008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002084815481101515613ba457fe5b906000526020600020906002020160008082016000905560018201600090555050600b60008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020613c5a6001600b60008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020805490506139cc90919063ffffffff16565b815481101515613c6657fe5b9060005260206000209060020201600b60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002085815481101515613cc057fe5b906000526020600020906002020160008201548160000155600182015481600101559050506001600b60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081818054905003915081613d3a9190613ece565b506000600b60008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020805490501415613ddf576000600860008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055505b8473ffffffffffffffffffffffffffffffffffffffff167f6381d9813cabeb57471b5a7e05078e64845ccdb563146a6911d536f24ce960f1826040518082815260200191505060405180910390a2613e7f81600760008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546139e590919063ffffffff16565b600760008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555060019250505092915050565b815481835581811115613efb57600202816002028360005260206000209182019101613efa9190613f00565b5b505050565b613f2c91905b80821115613f2857600080820160009055600182016000905550600201613f06565b5090565b9056fea165627a7a723058200652ea2b2f32a8394252fd1c4e3714b34f6180c1140ef40929f28d93bbaf432b0029
[ 16, 2, 18 ]
0x5de09699a9a81fb3ac2c62af09a835e35b5764db
pragma solidity 0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract EVERISTY is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function EVERISTY( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a7230582065be37117e4ca30f757952e34f56de6b7ff5f45d41430ea5a54a4663594685520029
[ 38 ]
0x5e0fa16e190f8de73ee7f415c47eed8315a7601e
pragma solidity 0.6.12; 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 Modifier to use in the initializer function of a contract when upgrade EVEN times. */ modifier initializerEven() { require(initializing || isConstructor() || initialized, "Contract instance has already been initialized EVEN times"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = false; } _; 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 Governable is Initializable { address public governor; event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor); /** * @dev Contract initializer. * called once by the factory at time of deployment */ function initialize(address governor_) virtual public initializer { governor = governor_; emit GovernorshipTransferred(address(0), governor); } modifier governance() { require(msg.sender == governor); _; } /** * @dev Allows the current governor to relinquish control of the contract. * @notice Renouncing to governorship will leave the contract without an governor. * It will not be possible to call the functions with the `governance` * modifier anymore. */ function renounceGovernorship() public governance { emit GovernorshipTransferred(governor, address(0)); governor = address(0); } /** * @dev Allows the current governor to transfer control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function transferGovernorship(address newGovernor) public governance { _transferGovernorship(newGovernor); } /** * @dev Transfers control of the contract to a newGovernor. * @param newGovernor The address to transfer governorship to. */ function _transferGovernorship(address newGovernor) internal { require(newGovernor != address(0)); emit GovernorshipTransferred(governor, newGovernor); governor = newGovernor; } } contract Configurable is Governable { mapping (bytes32 => uint) internal config; function getConfig(bytes32 key) public view returns (uint) { return config[key]; } function getConfig(bytes32 key, uint index) public view returns (uint) { return config[bytes32(uint(key) ^ index)]; } function getConfig(bytes32 key, address addr) public view returns (uint) { return config[bytes32(uint(key) ^ uint(addr))]; } function _setConfig(bytes32 key, uint value) internal { if(config[key] != value) config[key] = value; } function _setConfig(bytes32 key, uint index, uint value) internal { _setConfig(bytes32(uint(key) ^ index), value); } function _setConfig(bytes32 key, address addr, uint value) internal { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } function setConfig(bytes32 key, uint value) external governance { _setConfig(key, value); } function setConfig(bytes32 key, uint index, uint value) external governance { _setConfig(bytes32(uint(key) ^ index), value); } function setConfig(bytes32 key, address addr, uint value) external governance { _setConfig(bytes32(uint(key) ^ uint(addr)), value); } } interface Minter { event Minted(address indexed recipient, address reward_contract, uint minted); function token() external view returns (address); function controller() external view returns (address); function minted(address, address) external view returns (uint); function allowed_to_mint_for(address, address) external view returns (bool); function mint(address gauge) external; function mint_many(address[8] calldata gauges) external; function mint_for(address gauge, address _for) external; function toggle_approve_mint(address minting_user) external; } interface LiquidityGauge { event Deposit(address indexed provider, uint value); event Withdraw(address indexed provider, uint value); event UpdateLiquidityLimit(address user, uint original_balance, uint original_supply, uint working_balance, uint working_supply); function user_checkpoint (address addr) external returns (bool); function claimable_tokens(address addr) external view returns (uint); function claimable_reward(address addr) external view returns (uint); function integrate_checkpoint() external view returns (uint); function kick(address addr) external; function set_approve_deposit(address addr, bool can_deposit) external; function deposit(uint _value) external; function deposit(uint _value, address addr) external; function withdraw(uint _value) external; function withdraw(uint _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function minter() external view returns (address); function crv_token() external view returns (address); function lp_token() external view returns (address); function controller() external view returns (address); function voting_escrow() external view returns (address); function balanceOf(address) external view returns (uint); function totalSupply() external view returns (uint); function future_epoch_time() external view returns (uint); function approved_to_deposit(address, address) external view returns (bool); function working_balances(address) external view returns (uint); function working_supply() external view returns (uint); function period() external view returns (int128); function period_timestamp(uint) external view returns (uint); function integrate_inv_supply(uint) external view returns (uint); function integrate_inv_supply_of(address) external view returns (uint); function integrate_checkpoint_of(address) external view returns (uint); function integrate_fraction(address) external view returns (uint); function inflation_rate() external view returns (uint); function reward_contract() external view returns (address); function rewarded_token() external view returns (address); function reward_integral() external view returns (uint); function reward_integral_for(address) external view returns (uint); function rewards_for(address) external view returns (uint); function claimed_rewards_for(address) external view returns (uint); } contract SSimpleGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; uint override public reward_integral; mapping(address => uint) override public reward_integral_for; mapping(address => uint) override public rewards_for; mapping(address => uint) override public claimed_rewards_for; uint public span; uint public end; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[addr] = balanceOf[addr].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(addr, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool claim_rewards) virtual override public { _checkpoint(msg.sender, claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address) virtual override public view returns (uint) { return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = SMinter(minter).quotas(address(this)); amount = amount.mul(balanceOf[addr]).div(totalSupply); uint lasttime = integrate_checkpoint_of[addr]; if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); address teamAddr = address(config['teamAddr']); uint teamRatio = config['teamRatio']; if(teamAddr != address(0) && teamRatio != 0) integrate_fraction[teamAddr] = integrate_fraction[teamAddr].add(amount.mul(teamRatio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { uint amount = claimable_tokens(addr); _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); integrate_checkpoint_of[addr] = now; } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return now; } } c SExactGauge is LiquidityGauge, Configurable { using SafeMath for uint; using TransferHelper for address; bytes32 internal constant _devAddr_ = 'devAddr'; bytes32 internal constant _devRatio_ = 'devRatio'; bytes32 internal constant _ecoAddr_ = 'ecoAddr'; bytes32 internal constant _ecoRatio_ = 'ecoRatio'; address override public minter; address override public crv_token; address override public lp_token; address override public controller; address override public voting_escrow; mapping(address => uint) override public balanceOf; uint override public totalSupply; uint override public future_epoch_time; // caller -> recipient -> can deposit? mapping(address => mapping(address => bool)) override public approved_to_deposit; mapping(address => uint) override public working_balances; uint override public working_supply; // The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint // All values are kept in units of being multiplied by 1e18 int128 override public period; uint256[100000000000000000000000000000] override public period_timestamp; // 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes // 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint mapping(address => uint) override public integrate_inv_supply_of; mapping(address => uint) override public integrate_checkpoint_of; // ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint // Units: rate * t = already number of coins per address to issue mapping(address => uint) override public integrate_fraction; uint override public inflation_rate; // For tracking external rewards address override public reward_contract; address override public rewarded_token; uint override public reward_integral; mapping(address => uint) override public reward_integral_for; mapping(address => uint) override public rewards_for; mapping(address => uint) override public claimed_rewards_for; uint public span; uint public end; mapping(address => uint) public sumMiningPerOf; uint public sumMiningPer; uint public bufReward; uint public lasttime; function initialize(address governor, address _minter, address _lp_token) public initializer { super.initialize(governor); minter = _minter; crv_token = Minter(_minter).token(); lp_token = _lp_token; IERC20(lp_token).totalSupply(); // just check } function setSpan(uint _span, bool isLinear) virtual external governance { span = _span; if(isLinear) end = now + _span; else end = 0; lasttime = now; } function kick(address addr) virtual override external { _checkpoint(addr, true); } function set_approve_deposit(address addr, bool can_deposit) virtual override external { approved_to_deposit[addr][msg.sender] = can_deposit; } function deposit(uint amount) virtual override external { deposit(amount, msg.sender); } function deposit(uint amount, address addr) virtual override public { require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved'); _checkpoint(addr, true); _deposit(addr, amount); balanceOf[msg.sender] = balanceOf[msg.sender].add(amount); totalSupply = totalSupply.add(amount); emit Deposit(msg.sender, amount); } function _deposit(address addr, uint amount) virtual internal { lp_token.safeTransferFrom(addr, address(this), amount); } function withdraw() virtual external { withdraw(balanceOf[msg.sender], true); } function withdraw(uint amount) virtual override external { withdraw(amount, true); } function withdraw(uint amount, bool _claim_rewards) virtual override public { _checkpoint(msg.sender, _claim_rewards); totalSupply = totalSupply.sub(amount); balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount); _withdraw(msg.sender, amount); emit Withdraw(msg.sender, amount); } function _withdraw(address to, uint amount) virtual internal { lp_token.safeTransfer(to, amount); } function claimable_reward(address addr) virtual override public view returns (uint) { addr; return 0; } function claim_rewards() virtual override public { return claim_rewards(msg.sender); } function claim_rewards(address) virtual override public { return; } function _checkpoint_rewards(address, bool) virtual internal { return; } function claimable_tokens(address addr) virtual override public view returns (uint) { return _claimable_tokens(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr]); } function _claimable_tokens(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) { if(span == 0 || totalSupply == 0) return 0; amount = sumPer.sub(lastSumPer); amount = amount.add(delta.mul(1 ether).div(totalSupply)); amount = amount.mul(balanceOf[addr]).div(1 ether); } function claimableDelta() virtual internal view returns(uint amount) { amount = SMinter(minter).quotas(address(this)).sub(bufReward); if(end == 0) { // isNonLinear, endless if(now.sub(lasttime) < span) amount = amount.mul(now.sub(lasttime)).div(span); }else if(now < end) amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime)); else if(lasttime >= end) amount = 0; } function _checkpoint(address addr, uint amount) virtual internal { if(amount > 0) { integrate_fraction[addr] = integrate_fraction[addr].add(amount); addr = address(config[_devAddr_]); uint ratio = config[_devRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); addr = address(config[_ecoAddr_]); ratio = config[_ecoRatio_]; if(addr != address(0) && ratio != 0) integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether)); } } function _checkpoint(address addr, bool _claim_rewards) virtual internal { if(span == 0 || totalSupply == 0) return; uint delta = claimableDelta(); uint amount = _claimable_tokens(addr, delta, sumMiningPer, sumMiningPerOf[addr]); if(delta != amount) bufReward = bufReward.add(delta).sub(amount); if(delta > 0) sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(totalSupply)); if(sumMiningPerOf[addr] != sumMiningPer) sumMiningPerOf[addr] = sumMiningPer; lasttime = now; _checkpoint(addr, amount); _checkpoint_rewards(addr, _claim_rewards); } function user_checkpoint(address addr) virtual override external returns (bool) { _checkpoint(addr, true); return true; } function integrate_checkpoint() override external view returns (uint) { return lasttime; } } contra uge is SExactGauge { address[] public rewards; mapping(address => mapping(address =>uint)) public sumRewardPerOf; // recipient => rewarded_token => can sumRewardPerOf mapping(address => uint) public sumRewardPer; // rewarded_token => can sumRewardPerOf function initialize(address governor, address _minter, address _lp_token, address _nestGauge, address[] memory _moreRewards) public initializer { super.initialize(governor, _minter, _lp_token); reward_contract = _nestGauge; rewarded_token = LiquidityGauge(_nestGauge).crv_token(); rewards = _moreRewards; rewards.push(rewarded_token); address rewarded_token2 = LiquidityGauge(_nestGauge).rewarded_token(); if(rewarded_token2 != address(0)) rewards.push(rewarded_token2); LiquidityGauge(_nestGauge).integrate_checkpoint(); // just check for(uint i=0; i<_moreRewards.length; i++) IERC20(_moreRewards[i]).totalSupply(); // just check } function _deposit(address from, uint amount) virtual override internal { super._deposit(from, amount); // lp_token.safeTransferFrom(from, address(this), amount); lp_token.safeApprove(reward_contract, amount); LiquidityGauge(reward_contract).deposit(amount); } function _withdraw(address to, uint amount) virtual override internal { LiquidityGauge(reward_contract).withdraw(amount); super._withdraw(to, amount); // lp_token.safeTransfer(to, amount); } function claim_rewards(address to) virtual override public { if(span == 0 || totalSupply == 0) return; uint[] memory bals = new uint[](rewards.length); for(uint i=0; i<bals.length; i++) bals[i] = IERC20(rewards[i]).balanceOf(address(this)); Minter(LiquidityGauge(reward_contract).minter()).mint(reward_contract); LiquidityGauge(reward_contract).claim_rewards(); for(uint i=0; i<bals.length; i++) { uint delta = IERC20(rewards[i]).balanceOf(address(this)).sub(bals[i]); uint amount = _claimable_tokens(msg.sender, delta, sumRewardPer[rewards[i]], sumRewardPerOf[msg.sender][rewards[i]]); if(delta > 0) sumRewardPer[rewards[i]] = sumRewardPer[rewards[i]].add(delta.mul(1 ether).div(totalSupply)); if(sumRewardPerOf[msg.sender][rewards[i]] != sumRewardPer[rewards[i]]) sumRewardPerOf[msg.sender][rewards[i]] = sumRewardPer[rewards[i]]; if(amount > 0) { rewards[i].safeTransfer(to, amount); if(rewards[i] == rewarded_token) { rewards_for[to] = rewards_for[to].add(amount); claimed_rewards_for[to] = claimed_rewards_for[to].add(amount); } } } } function claimable_reward(address addr) virtual override public view returns (uint) { uint delta = LiquidityGauge(reward_contract).claimable_tokens(address(this)); return _claimable_tokens(addr, delta, sumRewardPer[rewarded_token], sumRewardPerOf[addr][rewarded_token]); } function claimable_reward2(address addr) virtual public view returns (uint) { uint delta = LiquidityGauge(reward_contract).claimable_reward(address(this)); address reward2 = LiquidityGauge(reward_contract).rewarded_token(); return _claimable_tokens(addr, delta, sumRewardPer[reward2], sumRewardPerOf[addr][reward2]); } } contrac is Minter, Configurable { using SafeMath for uint; using Address for address payable; using TransferHelper for address; bytes32 internal constant _allowContract_ = 'allowContract'; bytes32 internal constant _allowlist_ = 'allowlist'; bytes32 internal constant _blocklist_ = 'blocklist'; address override public token; address override public controller; mapping(address => mapping(address => uint)) override public minted; // user => reward_contract => value mapping(address => mapping(address => bool)) override public allowed_to_mint_for; // minter => user => can mint? mapping(address => uint) public quotas; // reward_contract => quota; function initialize(address governor, address token_) public initializer { super.initialize(governor); token = token_; } function setGaugeQuota(address gauge, uint quota) public governance { quotas[gauge] = quota; } function mint(address gauge) virtual override public { mint_for(gauge, msg.sender); } function mint_many(address[8] calldata gauges) virtual override external { for(uint i=0; i<gauges.length; i++) mint(gauges[i]); } function mint_for(address gauge, address _for) virtual override public { require(_for == msg.sender || allowed_to_mint_for[msg.sender][_for], 'Not approved'); require(quotas[gauge] > 0, 'No quota'); require(getConfig(_blocklist_, msg.sender) == 0, 'In blocklist'); bool isContract = msg.sender.isContract(); require(!isContract || config[_allowContract_] != 0 || getConfig(_allowlist_, msg.sender) != 0, 'No allowContract'); LiquidityGauge(gauge).user_checkpoint(_for); uint total_mint = LiquidityGauge(gauge).integrate_fraction(_for); uint to_mint = total_mint.sub(minted[_for][gauge]); if(to_mint != 0) { quotas[gauge] = quotas[gauge].sub(to_mint); token.safeTransfer(_for, to_mint); minted[_for][gauge] = total_mint; emit Minted(_for, gauge, total_mint); } } function toggle_approve_mint(address minting_user) virtual override external { allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[minting_user][msg.sender]; } } /* // he 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; } } 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; } function sqrt(uint x)public pure returns(uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } 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); } } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) public _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 public _totalSupply; string internal _name; string internal _symbol; 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) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view 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 is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } contract SfgToken is ERC20 { constructor(address SfgFarm) ERC20("Stable Finance Governance Token", "SFG") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfgFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } contract SfyToken is ERC20 { constructor(address SfyFarm) ERC20("Stable Finance Yield Token", "SFY") public { uint8 decimals = 18; _setupDecimals(decimals); _mint(SfyFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000 } } library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } }
0x608060405234801561001057600080fd5b50600436106103a45760003560e01c806387564d84116101e9578063d31f3f6d1161010f578063ef78d4fd116100ad578063f77c47911161007c578063f77c4791146109d0578063f8453e7c146109d8578063fd96044b14610aa3578063fec8ee0c14610ac9576103a4565b8063ef78d4fd14610966578063efbe1c1c14610985578063f301af421461098d578063f76c5955146109aa576103a4565b8063dfe05031116100e9578063dfe05031146108fa578063e152253614610902578063e6f1daf214610930578063e7c47e8414610938576103a4565b8063d31f3f6d146108a3578063ddf2be3f146108ab578063de263bfa146108d4576103a4565b8063b6aa515b11610187578063c0c53b8b11610156578063c0c53b8b146107f9578063c4d66de814610831578063cdf10baf14610857578063d2797b591461087d576103a4565b8063b6aa515b146107a6578063b6b55f25146107cc578063be5d1be9146107e9578063bf88a6ff146107f1576103a4565b80639bd324f2116101c35780639bd324f2146107205780639df4ed5614610746578063aaa626b61461076c578063b21544f314610774576103a4565b806387564d84146106b25780638ec872e3146106d757806396c55175146106fa576103a4565b806333134583116102ce5780636dd5b69d1161026c57806376d8b1171161023b57806376d8b1171461067457806381c0c2631461067c57806382c630661461068457806384e9bd7e1461068c576103a4565b80636dd5b69d146105e85780636e553f651461060557806370a08231146106315780637598108c14610657576103a4565b806343d7f86f116102a857806343d7f86f146105725780634b8200931461057a57806352665f47146105b457806365fe9451146105e0576103a4565b8063331345831461051f57806338d07436146105455780633ccfd60b1461056a576103a4565b806317e28089116103465780631d2747d4116103155780631d2747d4146104c457806323a58292146104f25780632585581f146104fa5780632e1a7d4d14610502576103a4565b806317e2808914610486578063180692d01461048e57806318160ddd146104965780631b9f546f1461049e576103a4565b806313ecb1ca1161038257806313ecb1ca1461040d57806313fa13681461043357806315fe96dc1461045957806316fa50b11461047e576103a4565b806307546172146103a957806309400707146103cd5780630c340a2414610405575b600080fd5b6103b1610ae6565b604080516001600160a01b039092168252519081900360200190f35b6103f3600480360360208110156103e357600080fd5b50356001600160a01b0316610af5565b60408051918252519081900360200190f35b6103b1610b13565b6103f36004803603602081101561042357600080fd5b50356001600160a01b0316610b22565b6103f36004803603602081101561044957600080fd5b50356001600160a01b0316610b34565b61047c6004803603604081101561046f57600080fd5b5080359060200135610b52565b005b6103b1610b77565b6103f3610b92565b6103f3610b98565b6103f3610baa565b6103f3600480360360208110156104b457600080fd5b50356001600160a01b0316610bb0565b61047c600480360360408110156104da57600080fd5b506001600160a01b0381351690602001351515610bce565b6103f3610c04565b6103f3610c16565b61047c6004803603602081101561051857600080fd5b5035610c28565b6103f36004803603602081101561053557600080fd5b50356001600160a01b0316610c36565b61047c6004803603604081101561055b57600080fd5b50803590602001351515610c83565b61047c610d0e565b6103f3610d2b565b6105a06004803603602081101561059057600080fd5b50356001600160a01b0316610d3d565b604080519115158252519081900360200190f35b6103f3600480360360408110156105ca57600080fd5b50803590602001356001600160a01b0316610d52565b6103f3610d6e565b6103f3600480360360208110156105fe57600080fd5b5035610d80565b61047c6004803603604081101561061b57600080fd5b50803590602001356001600160a01b0316610d92565b6103f36004803603602081101561064757600080fd5b50356001600160a01b0316610e95565b6103f36004803603602081101561066d57600080fd5b5035610ea7565b6103b1610ec7565b61047c610ed6565b6103b1610f37565b61047c600480360360208110156106a257600080fd5b50356001600160a01b0316610f46565b61047c600480360360408110156106c857600080fd5b508035906020013515156116c8565b6103f3600480360360408110156106ed57600080fd5b5080359060200135611733565b61047c6004803603602081101561071057600080fd5b50356001600160a01b0316611746565b6103f36004803603602081101561073657600080fd5b50356001600160a01b0316611751565b6103f36004803603602081101561075c57600080fd5b50356001600160a01b031661176f565b6103f361178d565b61047c6004803603606081101561078a57600080fd5b508035906001600160a01b03602082013516906040013561179f565b61047c600480360360208110156107bc57600080fd5b50356001600160a01b03166117cb565b61047c600480360360208110156107e257600080fd5b50356117eb565b6103f36117f5565b6103b16117fb565b61047c6004803603606081101561080f57600080fd5b506001600160a01b038135811691602081013582169160409091013516611816565b61047c6004803603602081101561084757600080fd5b50356001600160a01b03166119d8565b6103f36004803603602081101561086d57600080fd5b50356001600160a01b0316611ac9565b6103f36004803603602081101561089357600080fd5b50356001600160a01b0316611c35565b6103f3611d2c565b61047c600480360360608110156108c157600080fd5b5080359060208101359060400135611d3f565b6103f3600480360360208110156108ea57600080fd5b50356001600160a01b0316611d62565b6103b1611d80565b6105a06004803603604081101561091857600080fd5b506001600160a01b0381358116916020013516611d8f565b61047c611daf565b6103f36004803603604081101561094e57600080fd5b506001600160a01b0381358116916020013516611db8565b61096e611de1565b60408051600f9290920b8252519081900360200190f35b6103f3611dea565b6103b1600480360360208110156109a357600080fd5b5035611dfc565b6103f3600480360360208110156109c057600080fd5b50356001600160a01b0316611e2f565b6103b1611e4d565b61047c600480360360a08110156109ee57600080fd5b6001600160a01b03823581169260208101358216926040820135831692606083013516919081019060a081016080820135640100000000811115610a3157600080fd5b820183602082011115610a4357600080fd5b80359060200191846020830284011164010000000083111715610a6557600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250929550611e5c945050505050565b6103f360048036036020811015610ab957600080fd5b50356001600160a01b031661220f565b6103f360048036036020811015610adf57600080fd5b503561222d565b6035546001600160a01b031681565b6c02863c1f5cdae42f95400000436020526000908152604090205481565b6033546001600160a01b031681565b603e6020526000908152604090205481565b6c02863c1f5cdae42f95400000486020526000908152604090205481565b6033546001600160a01b03163314610b6957600080fd5b610b738282612252565b5050565b6c02863c1f5cdae42f9540000046546001600160a01b031681565b603f5481565b6c02863c1f5cdae42f95400000445481565b603b5481565b6c02863c1f5cdae42f954000004d6020526000908152604090205481565b6001600160a01b03919091166000908152603d602090815260408083203384529091529020805460ff1916911515919091179055565b6c02863c1f5cdae42f95400000505481565b6c02863c1f5cdae42f954000004b5481565b610c33816001610c83565b50565b6000610c7d82610c44612279565b6c02863c1f5cdae42f954000004e546001600160a01b03861660009081526c02863c1f5cdae42f954000004d60205260409020546123fe565b92915050565b610c8d338261249f565b603b54610c9a908361263b565b603b55336000908152603a6020526040902054610cb7908361263b565b336000818152603a6020526040902091909155610cd4908361267d565b60408051838152905133917f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364919081900360200190a25050565b336000908152603a6020526040902054610d29906001610c83565b565b6c02863c1f5cdae42f954000004f5481565b6000610d4a82600161249f565b506001919050565b6001600160a01b03161860009081526034602052604090205490565b6c02863c1f5cdae42f954000004e5481565b60009081526034602052604090205490565b6001600160a01b038116331480610dcc5750336000908152603d602090815260408083206001600160a01b038516845290915290205460ff165b610e0c576040805162461bcd60e51b815260206004820152600c60248201526b139bdd08185c1c1c9bdd995960a21b604482015290519081900360640190fd5b610e1781600161249f565b610e2181836126f8565b336000908152603a6020526040902054610e3b9083612798565b336000908152603a6020526040902055603b54610e589083612798565b603b5560408051838152905133917fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c919081900360200190a25050565b603a6020526000908152604090205481565b6041816c01431e0fae6d7217caa00000008110610ec057fe5b0154905081565b6036546001600160a01b031681565b6033546001600160a01b03163314610eed57600080fd5b6033546040516000916001600160a01b0316907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908390a3603380546001600160a01b0319169055565b6037546001600160a01b031681565b6c02863c1f5cdae42f954000004b541580610f615750603b54155b15610f6b57610c33565b6c02863c1f5cdae42f95400000515460609067ffffffffffffffff81118015610f9357600080fd5b50604051908082528060200260200182016040528015610fbd578160200160208202803683370190505b50905060005b8151811015611081576c02863c1f5cdae42f95400000518181548110610fe557fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b15801561103457600080fd5b505afa158015611048573d6000803e3d6000fd5b505050506040513d602081101561105e57600080fd5b5051825183908390811061106e57fe5b6020908102919091010152600101610fc3565b506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663075461726040518163ffffffff1660e01b815260040160206040518083038186803b1580156110dc57600080fd5b505afa1580156110f0573d6000803e3d6000fd5b505050506040513d602081101561110657600080fd5b50516c02863c1f5cdae42f954000004554604080516335313c2160e11b81526001600160a01b03928316600482015290519190921691636a62784291602480830192600092919082900301818387803b15801561116257600080fd5b505af1158015611176573d6000803e3d6000fd5b505050506c02863c1f5cdae42f954000004560009054906101000a90046001600160a01b03166001600160a01b031663e6f1daf26040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156111d657600080fd5b505af11580156111ea573d6000803e3d6000fd5b5050505060005b81518110156116c35760006112ad83838151811061120b57fe5b60200260200101516c02863c1f5cdae42f9540000051848154811061122c57fe5b60009182526020918290200154604080516370a0823160e01b815230600482015290516001600160a01b03909216926370a0823192602480840193829003018186803b15801561127b57600080fd5b505afa15801561128f573d6000803e3d6000fd5b505050506040513d60208110156112a557600080fd5b50519061263b565b9050600061136533836c02863c1f5cdae42f954000005360006c02863c1f5cdae42f954000005188815481106112df57fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120543382526c02863c1f5cdae42f95400000529093529081206c02863c1f5cdae42f954000005180549192918a90811061133b57fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020546123fe565b9050811561143357603b546113e4906113909061138a85670de0b6b3a76400006127f2565b9061284b565b6c02863c1f5cdae42f954000005360006c02863c1f5cdae42f954000005187815481106113b957fe5b60009182526020808320909101546001600160a01b0316835282019290925260400190205490612798565b6c02863c1f5cdae42f954000005360006c02863c1f5cdae42f9540000051868154811061140d57fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b6c02863c1f5cdae42f954000005360006c02863c1f5cdae42f9540000051858154811061145c57fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120543382526c02863c1f5cdae42f95400000529093529081206c02863c1f5cdae42f95400000518054919291879081106114b857fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020541461158d576c02863c1f5cdae42f954000005360006c02863c1f5cdae42f9540000051858154811061150b57fe5b60009182526020808320909101546001600160a01b031683528281019390935260409182018120543382526c02863c1f5cdae42f95400000529093529081206c02863c1f5cdae42f954000005180549192918790811061156757fe5b60009182526020808320909101546001600160a01b031683528201929092526040019020555b80156116b9576115cd85826c02863c1f5cdae42f954000005186815481106115b157fe5b6000918252602090912001546001600160a01b0316919061288d565b6c02863c1f5cdae42f9540000046546c02863c1f5cdae42f954000005180546001600160a01b03909216918590811061160257fe5b6000918252602090912001546001600160a01b031614156116b9576001600160a01b03851660009081526c02863c1f5cdae42f9540000049602052604090205461164c9082612798565b6001600160a01b03861660009081526c02863c1f5cdae42f954000004960209081526040808320939093556c02863c1f5cdae42f954000004a905220546116939082612798565b6001600160a01b03861660009081526c02863c1f5cdae42f954000004a60205260409020555b50506001016111f1565b505050565b6033546001600160a01b031633146116df57600080fd5b6c02863c1f5cdae42f954000004b829055801561170d574282016c02863c1f5cdae42f954000004c5561171f565b60006c02863c1f5cdae42f954000004c555b5050426c02863c1f5cdae42f954000005055565b1860009081526034602052604090205490565b610c3381600161249f565b6c02863c1f5cdae42f95400000426020526000908152604090205481565b6c02863c1f5cdae42f95400000496020526000908152604090205481565b6c02863c1f5cdae42f95400000475481565b6033546001600160a01b031633146117b657600080fd5b6116c36001600160a01b038316841882612252565b6033546001600160a01b031633146117e257600080fd5b610c33816129f7565b610c338133610d92565b603c5481565b6c02863c1f5cdae42f9540000045546001600160a01b031681565b600054610100900460ff168061182f575061182f612a66565b8061183d575060005460ff16155b6118785760405162461bcd60e51b815260040180806020018281038252602e8152602001806130e8602e913960400191505060405180910390fd5b600054610100900460ff161580156118a3576000805460ff1961ff0019909116610100171660011790555b6118ac846119d8565b603580546001600160a01b0319166001600160a01b03851690811790915560408051637e062a3560e11b8152905163fc0c546a91600480820192602092909190829003018186803b15801561190057600080fd5b505afa158015611914573d6000803e3d6000fd5b505050506040513d602081101561192a57600080fd5b5051603680546001600160a01b03199081166001600160a01b0393841617909155603780549091168483161790819055604080516318160ddd60e01b8152905191909216916318160ddd916004808301926020929190829003018186803b15801561199457600080fd5b505afa1580156119a8573d6000803e3d6000fd5b505050506040513d60208110156119be57600080fd5b505080156119d2576000805461ff00191690555b50505050565b600054610100900460ff16806119f157506119f1612a66565b806119ff575060005460ff16155b611a3a5760405162461bcd60e51b815260040180806020018281038252602e8152602001806130e8602e913960400191505060405180910390fd5b600054610100900460ff16158015611a65576000805460ff1961ff0019909116610100171660011790555b603380546001600160a01b0319166001600160a01b0384811691909117918290556040519116906000907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a908290a38015610b73576000805461ff00191690555050565b6c02863c1f5cdae42f9540000045546040805163d2797b5960e01b8152306004820152905160009283926001600160a01b039091169163d2797b5991602480820192602092909190829003018186803b158015611b2557600080fd5b505afa158015611b39573d6000803e3d6000fd5b505050506040513d6020811015611b4f57600080fd5b50516c02863c1f5cdae42f954000004554604080516316fa50b160e01b815290519293506000926001600160a01b03909216916316fa50b191600480820192602092909190829003018186803b158015611ba857600080fd5b505afa158015611bbc573d6000803e3d6000fd5b505050506040513d6020811015611bd257600080fd5b50516001600160a01b0380821660008181526c02863c1f5cdae42f95400000536020908152604080832054948a1683526c02863c1f5cdae42f954000005282528083209383529290522054919250611c2d91869185916123fe565b949350505050565b6c02863c1f5cdae42f95400000455460408051633313458360e01b8152306004820152905160009283926001600160a01b0390911691633313458391602480820192602092909190829003018186803b158015611c9157600080fd5b505afa158015611ca5573d6000803e3d6000fd5b505050506040513d6020811015611cbb57600080fd5b50516c02863c1f5cdae42f9540000046546001600160a01b0390811660008181526c02863c1f5cdae42f9540000053602090815260408083205494891683526c02863c1f5cdae42f954000005282528083209383529290522054919250611d2591859184916123fe565b9392505050565b6c02863c1f5cdae42f9540000050545b90565b6033546001600160a01b03163314611d5657600080fd5b6116c383831882612252565b6c02863c1f5cdae42f95400000416020526000908152604090205481565b6039546001600160a01b031681565b603d60209081526000928352604080842090915290825290205460ff1681565b610d2933610f46565b6c02863c1f5cdae42f954000005260209081526000928352604080842090915290825290205481565b604054600f0b81565b6c02863c1f5cdae42f954000004c5481565b6c02863c1f5cdae42f95400000518181548110611e1557fe5b6000918252602090912001546001600160a01b0316905081565b6c02863c1f5cdae42f95400000536020526000908152604090205481565b6038546001600160a01b031681565b600054610100900460ff1680611e755750611e75612a66565b80611e83575060005460ff16155b611ebe5760405162461bcd60e51b815260040180806020018281038252602e8152602001806130e8602e913960400191505060405180910390fd5b600054610100900460ff16158015611ee9576000805460ff1961ff0019909116610100171660011790555b611ef4868686611816565b6c02863c1f5cdae42f954000004580546001600160a01b0319166001600160a01b038516908117909155604080516376d8b11760e01b815290516376d8b11791600480820192602092909190829003018186803b158015611f5457600080fd5b505afa158015611f68573d6000803e3d6000fd5b505050506040513d6020811015611f7e57600080fd5b50516c02863c1f5cdae42f954000004680546001600160a01b0319166001600160a01b039092169190911790558151611fca906c02863c1f5cdae42f9540000051906020850190613042565b506c02863c1f5cdae42f9540000046546c02863c1f5cdae42f9540000051805460018101825560009182527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b03938416179055604080516316fa50b160e01b8152905191928616916316fa50b191600480820192602092909190829003018186803b15801561206c57600080fd5b505afa158015612080573d6000803e3d6000fd5b505050506040513d602081101561209657600080fd5b505190506001600160a01b03811615612101576c02863c1f5cdae42f954000005180546001810182556000919091527fc3a663b2abf67098c4ee9266947fc39af695e9ac338685a7b0e64b0d4464a7040180546001600160a01b0319166001600160a01b0383161790555b836001600160a01b031663d31f3f6d6040518163ffffffff1660e01b815260040160206040518083038186803b15801561213a57600080fd5b505afa15801561214e573d6000803e3d6000fd5b505050506040513d602081101561216457600080fd5b50600090505b83518110156121f35783818151811061217f57fe5b60200260200101516001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156121bf57600080fd5b505afa1580156121d3573d6000803e3d6000fd5b505050506040513d60208110156121e957600080fd5b505060010161216a565b50508015612207576000805461ff00191690555b505050505050565b6c02863c1f5cdae42f954000004a6020526000908152604090205481565b6c01431e0fae6d7217caa0000041816c01431e0fae6d7217caa00000008110610ec057fe5b6000828152603460205260409020548114610b735760009182526034602052604090912055565b6c02863c1f5cdae42f954000004f546035546040805163c33342e960e01b815230600482015290516000936122dc9390926001600160a01b039091169163c33342e991602480820192602092909190829003018186803b15801561127b57600080fd5b90506c02863c1f5cdae42f954000004c5460001415612369576c02863c1f5cdae42f954000004b546c02863c1f5cdae42f95400000505461231e90429061263b565b1015612364576123616c02863c1f5cdae42f954000004b5461138a61235a6c02863c1f5cdae42f9540000050544261263b90919063ffffffff16565b84906127f2565b90505b611d3c565b6c02863c1f5cdae42f954000004c544210156123d5576123616123b16c02863c1f5cdae42f9540000050546c02863c1f5cdae42f954000004c5461263b90919063ffffffff16565b61138a61235a6c02863c1f5cdae42f9540000050544261263b90919063ffffffff16565b6c02863c1f5cdae42f954000004c546c02863c1f5cdae42f95400000505410611d3c5750600090565b60006c02863c1f5cdae42f954000004b546000148061241d5750603b54155b1561242a57506000611c2d565b612434838361263b565b905061246161245a603b5461138a670de0b6b3a7640000886127f290919063ffffffff16565b8290612798565b6001600160a01b0386166000908152603a602052604090205490915061249690670de0b6b3a76400009061138a9084906127f2565b95945050505050565b6c02863c1f5cdae42f954000004b5415806124ba5750603b54155b156124c457610b73565b60006124ce612279565b9050600061251d84836c02863c1f5cdae42f954000004e546c02863c1f5cdae42f954000004d6000896001600160a01b03166001600160a01b03168152602001908152602001600020546123fe565b9050808214612561576125518161254b846c02863c1f5cdae42f954000004f5461279890919063ffffffff16565b9061263b565b6c02863c1f5cdae42f954000004f555b81156125a957603b54612599906125849061138a85670de0b6b3a76400006127f2565b6c02863c1f5cdae42f954000004e5490612798565b6c02863c1f5cdae42f954000004e555b6c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d602052604090205414612617576c02863c1f5cdae42f954000004e546001600160a01b03851660009081526c02863c1f5cdae42f954000004d60205260409020555b426c02863c1f5cdae42f9540000050556126318482612a6c565b6119d28484610b73565b6000611d2583836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612c5f565b6c02863c1f5cdae42f95400000455460408051632e1a7d4d60e01b81526004810184905290516001600160a01b0390921691632e1a7d4d9160248082019260009290919082900301818387803b1580156126d657600080fd5b505af11580156126ea573d6000803e3d6000fd5b50505050610b738282612cf6565b6127028282612d0d565b6c02863c1f5cdae42f95400000455460375461272b916001600160a01b03918216911683612d25565b6c02863c1f5cdae42f9540000045546040805163b6b55f2560e01b81526004810184905290516001600160a01b039092169163b6b55f259160248082019260009290919082900301818387803b15801561278457600080fd5b505af1158015612207573d6000803e3d6000fd5b600082820183811015611d25576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b60008261280157506000610c7d565b8282028284828161280e57fe5b0414611d255760405162461bcd60e51b81526004018080602001828103825260218152602001806130c76021913960400191505060405180910390fd5b6000611d2583836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f000000000000815250612e88565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b178152925182516000946060949389169392918291908083835b6020831061290a5780518252601f1990920191602091820191016128eb565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d806000811461296c576040519150601f19603f3d011682016040523d82523d6000602084013e612971565b606091505b509150915081801561299f57508051158061299f575080806020019051602081101561299c57600080fd5b50515b6129f0576040805162461bcd60e51b815260206004820152601f60248201527f5472616e7366657248656c7065723a205452414e534645525f4641494c454400604482015290519081900360640190fd5b5050505050565b6001600160a01b038116612a0a57600080fd5b6033546040516001600160a01b038084169216907fc7c0c772add429241571afb3805861fb3cfa2af374534088b76cdb4325a87e9a90600090a3603380546001600160a01b0319166001600160a01b0392909216919091179055565b303b1590565b8015610b73576001600160a01b03821660009081526c02863c1f5cdae42f95400000436020526040902054612aa19082612798565b6001600160a01b0392831660009081526c02863c1f5cdae42f95400000436020908152604082209290925560349091527fe9b68ca2b566af5bdfbb3361c12fcbb5dbf956c250bbd74cc175cc06ec62c7915467646576526174696f60c01b9091527fb8fbd2e70438ec482a0e7fc9b87580647182c1694aea1065027a1d634e92d6b9549092831615801590612b3557508015155b15612ba457612b7e612b53670de0b6b3a764000061138a85856127f2565b6001600160a01b03851660009081526c02863c1f5cdae42f9540000043602052604090205490612798565b6001600160a01b03841660009081526c02863c1f5cdae42f954000004360205260409020555b5060346020527f82e0b58992d24d827851dcbd63485b5933f9d3ae4c2ca50477d1437e73f6d342546765636f526174696f60c01b6000527ffc6561c6b7742261fbeab673eba1bedd2f5b1d7221f757ea8c9a87d664cfbed2549092506001600160a01b03831615801590612c1757508015155b156116c357612c35612b53670de0b6b3a764000061138a85856127f2565b6001600160a01b03841660009081526c02863c1f5cdae42f95400000436020526040902055505050565b60008184841115612cee5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015612cb3578181015183820152602001612c9b565b50505050905090810190601f168015612ce05780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b603754610b73906001600160a01b0316838361288d565b603754610b73906001600160a01b0316833084612eed565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663095ea7b360e01b178152925182516000946060949389169392918291908083835b60208310612da25780518252601f199092019160209182019101612d83565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612e04576040519150601f19603f3d011682016040523d82523d6000602084013e612e09565b606091505b5091509150818015612e37575080511580612e375750808060200190516020811015612e3457600080fd5b50515b6129f0576040805162461bcd60e51b815260206004820152601e60248201527f5472616e7366657248656c7065723a20415050524f56455f4641494c45440000604482015290519081900360640190fd5b60008183612ed75760405162461bcd60e51b8152602060048201818152835160248401528351909283926044909101919085019080838360008315612cb3578181015183820152602001612c9b565b506000838581612ee357fe5b0495945050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b17815292518251600094606094938a169392918291908083835b60208310612f725780518252601f199092019160209182019101612f53565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114612fd4576040519150601f19603f3d011682016040523d82523d6000602084013e612fd9565b606091505b5091509150818015613007575080511580613007575080806020019051602081101561300457600080fd5b50515b6122075760405162461bcd60e51b81526004018080602001828103825260248152602001806131166024913960400191505060405180910390fd5b828054828255906000526020600020908101928215613097579160200282015b8281111561309757825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190613062565b506130a39291506130a7565b5090565b5b808211156130a35780546001600160a01b03191681556001016130a856fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a65645472616e7366657248656c7065723a205452414e534645525f46524f4d5f4641494c4544a26469706673582212206b02ad16dfa67b5572ff949e5742c4dca28895c077ac77ec212a972b482daaf964736f6c634300060c0033
[ 5, 4, 9, 7 ]
0x5e491e9d7840c7c185f365d47ac6a1e967aa8e4c
pragma solidity 0.5.16; interface IBullswapCallee { function BullswapCall(address sender, uint amount0, uint amount1, bytes calldata data) external; } interface IBullswapERC20 { 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; } interface IBullswapFactory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IBullswapPair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } 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); } } contract BullswapERC20 is IBullswapERC20 { using SafeMath for uint; string public constant name = 'Bullswap'; string public constant symbol = 'BUL'; uint8 public constant decimals = 18; uint public totalSupply; mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; 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; event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); constructor() public { 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 _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external returns (bool) { if (allowance[from][msg.sender] != uint(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { require(deadline >= block.timestamp, 'Bullswap: 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); _approve(owner, spender, value); } } contract BullswapFactory is IBullswapFactory { address public feeTo; address public feeToSetter; mapping(address => mapping(address => address)) public getPair; address[] public allPairs; event PairCreated(address indexed token0, address indexed token1, address pair, uint); constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; } function allPairsLength() external view returns (uint) { return allPairs.length; } function createPair(address tokenA, address tokenB) external returns (address pair) { require(tokenA != tokenB, 'Bullswap: IDENTICAL_ADDRESSES'); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'Bullswap: ZERO_ADDRESS'); require(getPair[token0][token1] == address(0), 'Bullswap: PAIR_EXISTS'); // single check is sufficient bytes memory bytecode = type(BullswapPair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IBullswapPair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; // populate mapping in the reverse direction allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setFeeTo(address _feeTo) external { require(msg.sender == feeToSetter, 'Bullswap: FORBIDDEN'); feeTo = _feeTo; } function setFeeToSetter(address _feeToSetter) external { require(msg.sender == feeToSetter, 'Bullswap: FORBIDDEN'); feeToSetter = _feeToSetter; } } contract BullswapPair is IBullswapPair, BullswapERC20 { using SafeMath for uint; using UQ112x112 for uint224; uint public constant MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); address public factory; address public token0; address public token1; 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 uint public price0CumulativeLast; uint public price1CumulativeLast; uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint private unlocked = 1; modifier lock() { require(unlocked == 1, 'Bullswap: LOCKED'); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } function _safeTransfer(address token, address to, uint value) private { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'Bullswap: TRANSFER_FAILED'); } event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); constructor() public { factory = msg.sender; } // called once by the factory at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == factory, 'Bullswap: FORBIDDEN'); // sufficient check token0 = _token0; token1 = _token1; } // update reserves and, on the first call per block, price accumulators function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'Bullswap: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(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/6th of the growth in sqrt(k) function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { address feeTo = IBullswapFactory(factory).feeTo(); feeOn = feeTo != address(0); uint _kLast = kLast; // gas savings if (feeOn) { if (_kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)); uint denominator = rootK.mul(5).add(rootKLast); uint 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 (uint liquidity) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings uint balance0 = IERC20(token0).balanceOf(address(this)); uint balance1 = IERC20(token1).balanceOf(address(this)); uint amount0 = balance0.sub(_reserve0); uint amount1 = balance1.sub(_reserve1); bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); } require(liquidity > 0, 'Bullswap: INSUFFICIENT_LIQUIDITY_MINTED'); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date 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 (uint amount0, uint amount1) { (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings address _token0 = token0; // gas savings address _token1 = token1; // gas savings uint balance0 = IERC20(_token0).balanceOf(address(this)); uint balance1 = IERC20(_token1).balanceOf(address(this)); uint liquidity = balanceOf[address(this)]; bool feeOn = _mintFee(_reserve0, _reserve1); uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution require(amount0 > 0 && amount1 > 0, 'Bullswap: 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); if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date emit Burn(msg.sender, amount0, amount1, to); } // this low-level function should be called from a contract which performs important safety checks function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { require(amount0Out > 0 || amount1Out > 0, 'Bullswap: INSUFFICIENT_OUTPUT_AMOUNT'); (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings require(amount0Out < _reserve0 && amount1Out < _reserve1, 'Bullswap: INSUFFICIENT_LIQUIDITY'); uint balance0; uint balance1; { // scope for _token{0,1}, avoids stack too deep errors address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, 'Bullswap: INVALID_TO'); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens if (data.length > 0) IBullswapCallee(to).BullswapCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, 'Bullswap: INSUFFICIENT_INPUT_AMOUNT'); { // scope for reserve{0,1}Adjusted, avoids stack too deep errors uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'Bullswap: 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 { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _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); } }
0x608060405234801561001057600080fd5b50600436106100885760003560e01c8063a2e74af61161005b578063a2e74af6146100fd578063c9c6539614610132578063e6a439051461016d578063f46901ed146101a857610088565b8063017e7e581461008d578063094b7415146100be5780631e3dd18b146100c6578063574f2ba3146100e3575b600080fd5b6100956101db565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b6100956101f7565b610095600480360360208110156100dc57600080fd5b5035610213565b6100eb610247565b60408051918252519081900360200190f35b6101306004803603602081101561011357600080fd5b503573ffffffffffffffffffffffffffffffffffffffff1661024d565b005b6100956004803603604081101561014857600080fd5b5073ffffffffffffffffffffffffffffffffffffffff8135811691602001351661031a565b6100956004803603604081101561018357600080fd5b5073ffffffffffffffffffffffffffffffffffffffff8135811691602001351661076d565b610130600480360360208110156101be57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166107a0565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b60015473ffffffffffffffffffffffffffffffffffffffff1681565b6003818154811061022057fe5b60009182526020909120015473ffffffffffffffffffffffffffffffffffffffff16905081565b60035490565b60015473ffffffffffffffffffffffffffffffffffffffff1633146102d357604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f42756c6c737761703a20464f5242494444454e00000000000000000000000000604482015290519081900360640190fd5b600180547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b60008173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614156103b757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f42756c6c737761703a204944454e544943414c5f414444524553534553000000604482015290519081900360640190fd5b6000808373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff16106103f45783856103f7565b84845b909250905073ffffffffffffffffffffffffffffffffffffffff821661047e57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f42756c6c737761703a205a45524f5f4144445245535300000000000000000000604482015290519081900360640190fd5b73ffffffffffffffffffffffffffffffffffffffff82811660009081526002602090815260408083208585168452909152902054161561051f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f42756c6c737761703a20504149525f4558495354530000000000000000000000604482015290519081900360640190fd5b6060604051806020016105319061086d565b6020820181038252601f19601f82011660405250905060008383604051602001808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660601b81526014018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1660601b815260140192505050604051602081830303815290604052805190602001209050808251602084016000f5604080517f485cc95500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8781166004830152868116602483015291519297509087169163485cc9559160448082019260009290919082900301818387803b15801561065e57600080fd5b505af1158015610672573d6000803e3d6000fd5b5050505073ffffffffffffffffffffffffffffffffffffffff84811660008181526002602081815260408084208987168086529083528185208054978d167fffffffffffffffffffffffff000000000000000000000000000000000000000098891681179091559383528185208686528352818520805488168517905560038054600181018255958190527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b90950180549097168417909655925483519283529082015281517f0d3648bd0f6ba80134a33ba9275ac585d9d315f0ad8355cddefde31afa28d0e9929181900390910190a35050505092915050565b600260209081526000928352604080842090915290825290205473ffffffffffffffffffffffffffffffffffffffff1681565b60015473ffffffffffffffffffffffffffffffffffffffff16331461082657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f42756c6c737761703a20464f5242494444454e00000000000000000000000000604482015290519081900360640190fd5b600080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b612c898061087b8339019056fe60806040526001600c5534801561001557600080fd5b506040514690806052612c3782396040805191829003605201822082820182526008835267042756c6c737761760c41b6020938401528151808301835260018152603160f81b908401528151808401919091527fd3adcc028a94e4ded0c282ae8bd30c86a9081e960199e0bdf6f9be9542d81303818301527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6606082015260808101949094523060a0808601919091528151808603909101815260c09094019052825192019190912060035550600580546001600160a01b03191633179055612b34806101036000396000f3fe608060405234801561001057600080fd5b50600436106101b95760003560e01c80636a627842116100f9578063ba9a7a5611610097578063d21220a711610071578063d21220a7146105da578063d505accf146105e2578063dd62ed3e14610640578063fff6cae91461067b576101b9565b8063ba9a7a5614610597578063bc25cf771461059f578063c45a0155146105d2576101b9565b80637ecebe00116100d35780637ecebe00146104d757806389afcb441461050a57806395d89b4114610556578063a9059cbb1461055e576101b9565b80636a6278421461046957806370a082311461049c5780637464fc3d146104cf576101b9565b806323b872dd116101665780633644e515116101405780633644e51514610416578063485cc9551461041e5780635909c0d5146104595780635a3d549314610461576101b9565b806323b872dd146103ad57806330adf81f146103f0578063313ce567146103f8576101b9565b8063095ea7b311610197578063095ea7b3146103155780630dfe16811461036257806318160ddd14610393576101b9565b8063022c0d9f146101be57806306fdde03146102595780630902f1ac146102d6575b600080fd5b610257600480360360808110156101d457600080fd5b81359160208101359173ffffffffffffffffffffffffffffffffffffffff604083013516919081019060808101606082013564010000000081111561021857600080fd5b82018360208201111561022a57600080fd5b8035906020019184600183028401116401000000008311171561024c57600080fd5b509092509050610683565b005b610261610d6d565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561029b578181015183820152602001610283565b50505050905090810190601f1680156102c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102de610da6565b604080516dffffffffffffffffffffffffffff948516815292909316602083015263ffffffff168183015290519081900360600190f35b61034e6004803603604081101561032b57600080fd5b5073ffffffffffffffffffffffffffffffffffffffff8135169060200135610dfb565b604080519115158252519081900360200190f35b61036a610e12565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b61039b610e2e565b60408051918252519081900360200190f35b61034e600480360360608110156103c357600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060400135610e34565b61039b610f13565b610400610f37565b6040805160ff9092168252519081900360200190f35b61039b610f3c565b6102576004803603604081101561043457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516610f42565b61039b61101b565b61039b611021565b61039b6004803603602081101561047f57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16611027565b61039b600480360360208110156104b257600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113e1565b61039b6113f3565b61039b600480360360208110156104ed57600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166113f9565b61053d6004803603602081101561052057600080fd5b503573ffffffffffffffffffffffffffffffffffffffff1661140b565b6040805192835260208301919091528051918290030190f35b6102616118a8565b61034e6004803603604081101561057457600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81351690602001356118e1565b61039b6118ee565b610257600480360360208110156105b557600080fd5b503573ffffffffffffffffffffffffffffffffffffffff166118f4565b61036a611aea565b61036a611b06565b610257600480360360e08110156105f857600080fd5b5073ffffffffffffffffffffffffffffffffffffffff813581169160208101359091169060408101359060608101359060ff6080820135169060a08101359060c00135611b22565b61039b6004803603604081101561065657600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516611d14565b610257611d31565b600c546001146106f457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f42756c6c737761703a204c4f434b454400000000000000000000000000000000604482015290519081900360640190fd5b6000600c55841515806107075750600084115b61075c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526024815260200180612adc6024913960400191505060405180910390fd5b600080610767610da6565b5091509150816dffffffffffffffffffffffffffff168710801561079a5750806dffffffffffffffffffffffffffff1686105b61080557604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820181905260248201527f42756c6c737761703a20494e53554646494349454e545f4c4951554944495459604482015290519081900360640190fd5b600654600754600091829173ffffffffffffffffffffffffffffffffffffffff91821691908116908916821480159061086a57508073ffffffffffffffffffffffffffffffffffffffff168973ffffffffffffffffffffffffffffffffffffffff1614155b6108d557604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f42756c6c737761703a20494e56414c49445f544f000000000000000000000000604482015290519081900360640190fd5b8a156108e6576108e6828a8d611f17565b89156108f7576108f7818a8c611f17565b86156109d9578873ffffffffffffffffffffffffffffffffffffffff16635789efaf338d8d8c8c6040518663ffffffff1660e01b8152600401808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f8201169050808301925050509650505050505050600060405180830381600087803b1580156109c057600080fd5b505af11580156109d4573d6000803e3d6000fd5b505050505b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8416916370a08231916024808301926020929190829003018186803b158015610a4557600080fd5b505afa158015610a59573d6000803e3d6000fd5b505050506040513d6020811015610a6f57600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191955073ffffffffffffffffffffffffffffffffffffffff8316916370a0823191602480820192602092909190829003018186803b158015610ae157600080fd5b505afa158015610af5573d6000803e3d6000fd5b505050506040513d6020811015610b0b57600080fd5b5051925060009150506dffffffffffffffffffffffffffff85168a90038311610b35576000610b4b565b89856dffffffffffffffffffffffffffff160383035b9050600089856dffffffffffffffffffffffffffff16038311610b6f576000610b85565b89856dffffffffffffffffffffffffffff160383035b90506000821180610b965750600081115b610beb576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526023815260200180612ab96023913960400191505060405180910390fd5b6000610c1f610c0184600363ffffffff61212416565b610c13876103e863ffffffff61212416565b9063ffffffff6121aa16565b90506000610c37610c0184600363ffffffff61212416565b9050610c6f620f4240610c636dffffffffffffffffffffffffffff8b8116908b1663ffffffff61212416565b9063ffffffff61212416565b610c7f838363ffffffff61212416565b1015610cec57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152600b60248201527f42756c6c737761703a204b000000000000000000000000000000000000000000604482015290519081900360640190fd5b5050610cfa8484888861221c565b60408051838152602081018390528082018d9052606081018c9052905173ffffffffffffffffffffffffffffffffffffffff8b169133917fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8229181900360800190a350506001600c55505050505050505050565b6040518060400160405280600881526020017f42756c6c7377617000000000000000000000000000000000000000000000000081525081565b6008546dffffffffffffffffffffffffffff808216926e0100000000000000000000000000008304909116917c0100000000000000000000000000000000000000000000000000000000900463ffffffff1690565b6000610e083384846124d8565b5060015b92915050565b60065473ffffffffffffffffffffffffffffffffffffffff1681565b60005481565b73ffffffffffffffffffffffffffffffffffffffff831660009081526002602090815260408083203384529091528120547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff14610efe5773ffffffffffffffffffffffffffffffffffffffff84166000908152600260209081526040808320338452909152902054610ecc908363ffffffff6121aa16565b73ffffffffffffffffffffffffffffffffffffffff851660009081526002602090815260408083203384529091529020555b610f09848484612547565b5060019392505050565b7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b601281565b60035481565b60055473ffffffffffffffffffffffffffffffffffffffff163314610fc857604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601360248201527f42756c6c737761703a20464f5242494444454e00000000000000000000000000604482015290519081900360640190fd5b6006805473ffffffffffffffffffffffffffffffffffffffff9384167fffffffffffffffffffffffff00000000000000000000000000000000000000009182161790915560078054929093169116179055565b60095481565b600a5481565b6000600c5460011461109a57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f42756c6c737761703a204c4f434b454400000000000000000000000000000000604482015290519081900360640190fd5b6000600c819055806110aa610da6565b50600654604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905193955091935060009273ffffffffffffffffffffffffffffffffffffffff909116916370a08231916024808301926020929190829003018186803b15801561112457600080fd5b505afa158015611138573d6000803e3d6000fd5b505050506040513d602081101561114e57600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905192935060009273ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b1580156111c757600080fd5b505afa1580156111db573d6000803e3d6000fd5b505050506040513d60208110156111f157600080fd5b505190506000611217836dffffffffffffffffffffffffffff871663ffffffff6121aa16565b9050600061123b836dffffffffffffffffffffffffffff871663ffffffff6121aa16565b905060006112498787612628565b60005490915080611286576112726103e8610c1361126d878763ffffffff61212416565b6127b4565b985061128160006103e8612806565b6112e3565b6112e06dffffffffffffffffffffffffffff89166112aa868463ffffffff61212416565b816112b157fe5b046dffffffffffffffffffffffffffff89166112d3868563ffffffff61212416565b816112da57fe5b046128b6565b98505b6000891161133c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526027815260200180612a926027913960400191505060405180910390fd5b6113468a8a612806565b61135286868a8a61221c565b811561139457600854611390906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff61212416565b600b555b6040805185815260208101859052815133927f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f928290030190a250506001600c5550949695505050505050565b60016020526000908152604090205481565b600b5481565b60046020526000908152604090205481565b600080600c5460011461147f57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f42756c6c737761703a204c4f434b454400000000000000000000000000000000604482015290519081900360640190fd5b6000600c8190558061148f610da6565b50600654600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905194965092945073ffffffffffffffffffffffffffffffffffffffff9182169391169160009184916370a08231916024808301926020929190829003018186803b15801561151157600080fd5b505afa158015611525573d6000803e3d6000fd5b505050506040513d602081101561153b57600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191925060009173ffffffffffffffffffffffffffffffffffffffff8516916370a08231916024808301926020929190829003018186803b1580156115af57600080fd5b505afa1580156115c3573d6000803e3d6000fd5b505050506040513d60208110156115d957600080fd5b5051306000908152600160205260408120549192506115f88888612628565b6000549091508061160f848763ffffffff61212416565b8161161657fe5b049a508061162a848663ffffffff61212416565b8161163157fe5b04995060008b118015611644575060008a115b611699576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526027815260200180612a6b6027913960400191505060405180910390fd5b6116a330846128ce565b6116ae878d8d611f17565b6116b9868d8c611f17565b604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff8916916370a08231916024808301926020929190829003018186803b15801561172557600080fd5b505afa158015611739573d6000803e3d6000fd5b505050506040513d602081101561174f57600080fd5b5051604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905191965073ffffffffffffffffffffffffffffffffffffffff8816916370a0823191602480820192602092909190829003018186803b1580156117c157600080fd5b505afa1580156117d5573d6000803e3d6000fd5b505050506040513d60208110156117eb57600080fd5b505193506117fb85858b8b61221c565b811561183d57600854611839906dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041663ffffffff61212416565b600b555b604080518c8152602081018c9052815173ffffffffffffffffffffffffffffffffffffffff8f169233927fdccd412f0b1252819cb1fd330b93224ca42612892bb3f4f789976e6d81936496929081900390910190a35050505050505050506001600c81905550915091565b6040518060400160405280600381526020017f42554c000000000000000000000000000000000000000000000000000000000081525081565b6000610e08338484612547565b6103e881565b600c5460011461196557604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f42756c6c737761703a204c4f434b454400000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654600754600854604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff9485169490931692611a419285928792611a3c926dffffffffffffffffffffffffffff169185916370a0823191602480820192602092909190829003018186803b158015611a0457600080fd5b505afa158015611a18573d6000803e3d6000fd5b505050506040513d6020811015611a2e57600080fd5b50519063ffffffff6121aa16565b611f17565b600854604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611ae09284928792611a3c926e01000000000000000000000000000090046dffffffffffffffffffffffffffff169173ffffffffffffffffffffffffffffffffffffffff8616916370a0823191602480820192602092909190829003018186803b158015611a0457600080fd5b50506001600c5550565b60055473ffffffffffffffffffffffffffffffffffffffff1681565b60075473ffffffffffffffffffffffffffffffffffffffff1681565b42841015611b9157604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601160248201527f42756c6c737761703a2045585049524544000000000000000000000000000000604482015290519081900360640190fd5b60035473ffffffffffffffffffffffffffffffffffffffff80891660008181526004602090815260408083208054600180820190925582517f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c98186015280840196909652958d166060860152608085018c905260a085019590955260c08085018b90528151808603909101815260e0850182528051908301207f19010000000000000000000000000000000000000000000000000000000000006101008601526101028501969096526101228085019690965280518085039096018652610142840180825286519683019690962095839052610162840180825286905260ff89166101828501526101a284018890526101c28401879052519193926101e2808201937fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe081019281900390910190855afa158015611cf2573d6000803e3d6000fd5b505050602060405103519050611d098989896124d8565b505050505050505050565b600260209081526000928352604080842090915290825290205481565b600c54600114611da257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f42756c6c737761703a204c4f434b454400000000000000000000000000000000604482015290519081900360640190fd5b6000600c55600654604080517f70a082310000000000000000000000000000000000000000000000000000000081523060048201529051611f109273ffffffffffffffffffffffffffffffffffffffff16916370a08231916024808301926020929190829003018186803b158015611e1957600080fd5b505afa158015611e2d573d6000803e3d6000fd5b505050506040513d6020811015611e4357600080fd5b5051600754604080517f70a08231000000000000000000000000000000000000000000000000000000008152306004820152905173ffffffffffffffffffffffffffffffffffffffff909216916370a0823191602480820192602092909190829003018186803b158015611eb657600080fd5b505afa158015611eca573d6000803e3d6000fd5b505050506040513d6020811015611ee057600080fd5b50516008546dffffffffffffffffffffffffffff808216916e01000000000000000000000000000090041661221c565b6001600c55565b604080518082018252601981527f7472616e7366657228616464726573732c75696e743235362900000000000000602091820152815173ffffffffffffffffffffffffffffffffffffffff85811660248301526044808301869052845180840390910181526064909201845291810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fa9059cbb000000000000000000000000000000000000000000000000000000001781529251815160009460609489169392918291908083835b6020831061201d57805182527fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe09092019160209182019101611fe0565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d806000811461207f576040519150601f19603f3d011682016040523d82523d6000602084013e612084565b606091505b50915091508180156120b25750805115806120b257508080602001905160208110156120af57600080fd5b50515b61211d57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f42756c6c737761703a205452414e534645525f4641494c454400000000000000604482015290519081900360640190fd5b5050505050565b600081158061213f5750508082028282828161213c57fe5b04145b610e0c57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6d756c2d6f766572666c6f77000000000000000000000000604482015290519081900360640190fd5b80820382811115610e0c57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601560248201527f64732d6d6174682d7375622d756e646572666c6f770000000000000000000000604482015290519081900360640190fd5b6dffffffffffffffffffffffffffff841180159061224857506dffffffffffffffffffffffffffff8311155b6122b357604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601260248201527f42756c6c737761703a204f564552464c4f570000000000000000000000000000604482015290519081900360640190fd5b60085463ffffffff428116917c01000000000000000000000000000000000000000000000000000000009004811682039081161580159061230357506dffffffffffffffffffffffffffff841615155b801561231e57506dffffffffffffffffffffffffffff831615155b156123ce578063ffffffff166123618561233786612993565b7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff169063ffffffff6129b716565b600980547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff929092169290920201905563ffffffff81166123a18461233787612993565b600a80547bffffffffffffffffffffffffffffffffffffffffffffffffffffffff92909216929092020190555b600880547fffffffffffffffffffffffffffffffffffff0000000000000000000000000000166dffffffffffffffffffffffffffff888116919091177fffffffff0000000000000000000000000000ffffffffffffffffffffffffffff166e0100000000000000000000000000008883168102919091177bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167c010000000000000000000000000000000000000000000000000000000063ffffffff871602179283905560408051848416815291909304909116602082015281517f1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1929181900390910190a1505050505050565b73ffffffffffffffffffffffffffffffffffffffff808416600081815260026020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b73ffffffffffffffffffffffffffffffffffffffff831660009081526001602052604090205461257d908263ffffffff6121aa16565b73ffffffffffffffffffffffffffffffffffffffff80851660009081526001602052604080822093909355908416815220546125bf908263ffffffff6129f816565b73ffffffffffffffffffffffffffffffffffffffff80841660008181526001602090815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600080600560009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663017e7e586040518163ffffffff1660e01b815260040160206040518083038186803b15801561269357600080fd5b505afa1580156126a7573d6000803e3d6000fd5b505050506040513d60208110156126bd57600080fd5b5051600b5473ffffffffffffffffffffffffffffffffffffffff82161580159450919250906127a057801561279b57600061271461126d6dffffffffffffffffffffffffffff88811690881663ffffffff61212416565b90506000612721836127b4565b90508082111561279857600061274f612740848463ffffffff6121aa16565b6000549063ffffffff61212416565b905060006127748361276886600563ffffffff61212416565b9063ffffffff6129f816565b9050600081838161278157fe5b0490508015612794576127948782612806565b5050505b50505b6127ac565b80156127ac576000600b555b505092915050565b600060038211156127f7575080600160028204015b818110156127f1578091506002818285816127e057fe5b0401816127e957fe5b0490506127c9565b50612801565b8115612801575060015b919050565b600054612819908263ffffffff6129f816565b600090815573ffffffffffffffffffffffffffffffffffffffff8316815260016020526040902054612851908263ffffffff6129f816565b73ffffffffffffffffffffffffffffffffffffffff831660008181526001602090815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b60008183106128c557816128c7565b825b9392505050565b73ffffffffffffffffffffffffffffffffffffffff8216600090815260016020526040902054612904908263ffffffff6121aa16565b73ffffffffffffffffffffffffffffffffffffffff83166000908152600160205260408120919091555461293e908263ffffffff6121aa16565b600090815560408051838152905173ffffffffffffffffffffffffffffffffffffffff8516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef919081900360200190a35050565b6dffffffffffffffffffffffffffff166e0100000000000000000000000000000290565b60006dffffffffffffffffffffffffffff82167bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8416816129f057fe5b049392505050565b80820182811015610e0c57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601460248201527f64732d6d6174682d6164642d6f766572666c6f77000000000000000000000000604482015290519081900360640190fdfe42756c6c737761703a20494e53554646494349454e545f4c49515549444954595f4255524e454442756c6c737761703a20494e53554646494349454e545f4c49515549444954595f4d494e54454442756c6c737761703a20494e53554646494349454e545f494e5055545f414d4f554e5442756c6c737761703a20494e53554646494349454e545f4f55545055545f414d4f554e54a265627a7a723158208c9c7c62c3f6cb9d1459c60086940bc7456cfb8db3a45f605f8d6ec5154a428d64736f6c63430005100032454950373132446f6d61696e28737472696e67206e616d652c737472696e672076657273696f6e2c75696e7432353620636861696e49642c6164647265737320766572696679696e67436f6e747261637429a265627a7a723158207fc862eb11a02a74a228e7659aef90c57346f0cd294eb4602e2694f0ba14062064736f6c63430005100032
[ 10, 7, 9 ]
0x5ee8abac67c798f9a11ed5dcc2c49faf2b5359e0
pragma solidity 0.5.1; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function ceil(uint256 a, uint256 m) internal pure returns (uint256) { uint256 c = add(a,m); uint256 d = sub(c,1); return mul(div(d,m),m); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } contract ThisIsFine is ERC20Detailed { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => uint256) private _adminBalances; mapping (address => mapping (address => uint256)) private _allowed; string constant tokenName = "This is Fine: an announced rug"; string constant tokenSymbol = "TIF"; uint8 constant tokenDecimals = 18; uint256 _totalSupply = 100000000000000000000; // 100 TIF total supply uint256 _OwnerSupply = 100000000000000000000; // All supply is going to the contractOwner uint256 public burnPercent = 200; // 2% deflation each Tx uint256 private _releaseTime = 0; uint256 private _released; address public contractOwner; constructor() public payable ERC20Detailed(tokenName, tokenSymbol, tokenDecimals) { _released = block.timestamp+_releaseTime; contractOwner = msg.sender; _mint(msg.sender, _OwnerSupply); } modifier isOwner(){ require(msg.sender == contractOwner, "Unauthorised Sender"); _; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Returns when the Admin Funds will be released in seconds */ function released() public view returns (uint256) { return _released; } /** * @dev Gets the Admin balance of the specified address. * @param adminAddress The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function adminBalance(address adminAddress) public view returns(uint256) { return _adminBalances[adminAddress]; } /** * @dev Gets the balance of the specified address. * @param user The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address user) public view returns (uint256) { return _balances[user]; } //Finding the percent of the burnfee function findBurnPercent(uint256 value) internal view returns (uint256) { //Burn 1% of the sellers tokens uint256 burnValue = value.ceil(1); uint256 onePercent = burnValue.mul(burnPercent).div(10000); return onePercent; } //Simple transfer Does not burn tokens when transfering only allowed by Owner function simpleTransfer(address to, uint256 value) public isOwner returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } //Send Locked token to contract only Owner Can do so its pointless for anyone else function sendLockedToken(address beneficiary, uint256 value) public isOwner{ require(_released > block.timestamp, "TokenTimelock: release time is before current time"); require(value <= _balances[msg.sender]); _balances[msg.sender] = _balances[msg.sender].sub(value); _adminBalances[beneficiary] = value; } //Anyone Can Release The Funds after 2 months function release() public returns(bool){ require(block.timestamp >= _released, "TokenTimelock: current time is before release time"); uint256 value = _adminBalances[msg.sender]; require(value > 0, "TokenTimelock: no tokens to release"); _balances[msg.sender] = _balances[msg.sender].add(value); emit Transfer(contractOwner , msg.sender, value); return true; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ //To be Used by users to trasnfer tokens and burn while doing so function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender],"Not Enough Tokens in Account"); require(to != address(0)); uint256 burn; burn = findBurnPercent(value); uint256 tokensToTransfer = value.sub(burn); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(burn); emit Transfer(msg.sender, to, tokensToTransfer); emit Transfer(msg.sender, address(0), burn); return true; } //Transfer tokens to multiple addresses at once function multiTransfer(address[] memory receivers, uint256[] memory amounts) public { for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); } } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(amount != 0); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external { require(amount <= _balances[msg.sender],"Not Enough Tokens in Account"); _burn(msg.sender, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be Deflationary. * @param amount The amount that will be Deflationary. */ function _burn(address account, uint256 amount) internal { require(amount != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be Deflationary. * @param amount The amount that will be Deflationary. */ function burnFrom(address account, uint256 amount) external { require(amount <= _allowed[account][msg.sender]); _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(amount); _burn(account, amount); } /** * @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 Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); //Delete balance of this account _balances[from] = _balances[from].sub(value); uint256 burn; burn = findBurnPercent(value); uint256 tokensToTransfer = value.sub(burn); _balances[to] = _balances[to].add(tokensToTransfer); _totalSupply = _totalSupply.sub(burn); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, tokensToTransfer); emit Transfer(from, address(0), burn); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = (_allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } }
0x608060405260043610610117576000357c01000000000000000000000000000000000000000000000000000000009004806303807ee51461011c57806306fdde0314610147578063095ea7b3146101d757806318160ddd1461024a5780631e89d5451461027557806323b872dd146103ce578063313ce56714610461578063348f9d3e14610492578063395093511461050557806342966c681461057857806370a08231146105b357806379cc67901461061857806386d1a69f1461067357806395d89b41146106a25780639613252114610732578063a457c2d71461075d578063a9059cbb146107d0578063c4ae93b014610843578063ce606ee0146108a8578063dd62ed3e146108ff578063fa12e47614610984575b600080fd5b34801561012857600080fd5b506101316109df565b6040518082815260200191505060405180910390f35b34801561015357600080fd5b5061015c6109e5565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561019c578082015181840152602081019050610181565b50505050905090810190601f1680156101c95780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101e357600080fd5b50610230600480360360408110156101fa57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610a87565b604051808215151515815260200191505060405180910390f35b34801561025657600080fd5b5061025f610bb4565b6040518082815260200191505060405180910390f35b34801561028157600080fd5b506103cc6004803603604081101561029857600080fd5b81019080803590602001906401000000008111156102b557600080fd5b8201836020820111156102c757600080fd5b803590602001918460208302840111640100000000831117156102e957600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f8201169050808301925050505050505091929192908035906020019064010000000081111561034957600080fd5b82018360208201111561035b57600080fd5b8035906020019184602083028401116401000000008311171561037d57600080fd5b919080806020026020016040519081016040528093929190818152602001838360200280828437600081840152601f19601f820116905080830192505050505050509192919290505050610bbe565b005b3480156103da57600080fd5b50610447600480360360608110156103f157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610c18565b604051808215151515815260200191505060405180910390f35b34801561046d57600080fd5b5061047661107f565b604051808260ff1660ff16815260200191505060405180910390f35b34801561049e57600080fd5b506104eb600480360360408110156104b557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611096565b604051808215151515815260200191505060405180910390f35b34801561051157600080fd5b5061055e6004803603604081101561052857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611380565b604051808215151515815260200191505060405180910390f35b34801561058457600080fd5b506105b16004803603602081101561059b57600080fd5b81019080803590602001909291905050506115b7565b005b3480156105bf57600080fd5b50610602600480360360208110156105d657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061167b565b6040518082815260200191505060405180910390f35b34801561062457600080fd5b506106716004803603604081101561063b57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506116c4565b005b34801561067f57600080fd5b5061068861186c565b604051808215151515815260200191505060405180910390f35b3480156106ae57600080fd5b506106b7611b14565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156106f75780820151818401526020810190506106dc565b50505050905090810190601f1680156107245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561073e57600080fd5b50610747611bb6565b6040518082815260200191505060405180910390f35b34801561076957600080fd5b506107b66004803603604081101561078057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611bc0565b604051808215151515815260200191505060405180910390f35b3480156107dc57600080fd5b50610829600480360360408110156107f357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050611df7565b604051808215151515815260200191505060405180910390f35b34801561084f57600080fd5b506108926004803603602081101561086657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061212c565b6040518082815260200191505060405180910390f35b3480156108b457600080fd5b506108bd612175565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34801561090b57600080fd5b5061096e6004803603604081101561092257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061219b565b6040518082815260200191505060405180910390f35b34801561099057600080fd5b506109dd600480360360408110156109a757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050612222565b005b60085481565b606060008054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a7d5780601f10610a5257610100808354040283529160200191610a7d565b820191906000526020600020905b815481529060010190602001808311610a6057829003601f168201915b5050505050905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610ac457600080fd5b81600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b6000600654905090565b60008090505b8251811015610c1357610c058382815181101515610bde57fe5b906020019060200201518383815181101515610bf657fe5b90602001906020020151611df7565b508080600101915050610bc4565b505050565b6000600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515610c6857600080fd5b600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515610cf357600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515610d2f57600080fd5b610d8182600360008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506000610dcf836124ca565b90506000610de682856124b190919063ffffffff16565b9050610e3a81600360008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461251a90919063ffffffff16565b600360008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610e92826006546124b190919063ffffffff16565b600681905550610f2784600560008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600560008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508473ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3600073ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001925050509392505050565b6000600260009054906101000a900460ff16905090565b6000600b60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561115d576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f556e617574686f72697365642053656e6465720000000000000000000000000081525060200191505060405180910390fd5b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482111515156111ab57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141515156111e757600080fd5b61123982600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506112ce82600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461251a90919063ffffffff16565b600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16141515156113bd57600080fd5b61144c82600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461251a90919063ffffffff16565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054811115151561166e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f4e6f7420456e6f75676820546f6b656e7320696e204163636f756e740000000081525060200191505060405180910390fd5b6116783382612538565b50565b6000600360008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600560008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054811115151561174f57600080fd5b6117de81600560008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506118688282612538565b5050565b6000600a54421015151561190e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260328152602001807f546f6b656e54696d656c6f636b3a2063757272656e742074696d65206973206281526020017f65666f72652072656c656173652074696d65000000000000000000000000000081525060400191505060405180910390fd5b6000600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205490506000811115156119f0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001807f546f6b656e54696d656c6f636b3a206e6f20746f6b656e7320746f2072656c6581526020017f617365000000000000000000000000000000000000000000000000000000000081525060400191505060405180910390fd5b611a4281600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461251a90919063ffffffff16565b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055503373ffffffffffffffffffffffffffffffffffffffff16600b60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3600191505090565b606060018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015611bac5780601f10611b8157610100808354040283529160200191611bac565b820191906000526020600020905b815481529060010190602001808311611b8f57829003601f168201915b5050505050905090565b6000600a54905090565b60008073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515611bfd57600080fd5b611c8c82600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600560003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546040518082815260200191505060405180910390a36001905092915050565b6000600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020548211151515611eb0576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601c8152602001807f4e6f7420456e6f75676820546f6b656e7320696e204163636f756e740000000081525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614151515611eec57600080fd5b6000611ef7836124ca565b90506000611f0e82856124b190919063ffffffff16565b9050611f6284600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550611ff781600360008873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461251a90919063ffffffff16565b600360008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061204f826006546124b190919063ffffffff16565b6006819055508473ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3600073ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a360019250505092915050565b6000600460008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600b60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000600560008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600b60009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156122e7576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260138152602001807f556e617574686f72697365642053656e6465720000000000000000000000000081525060200191505060405180910390fd5b42600a54111515612386576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260328152602001807f546f6b656e54696d656c6f636b3a2072656c656173652074696d65206973206281526020017f65666f72652063757272656e742074696d65000000000000000000000000000081525060400191505060405180910390fd5b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205481111515156123d457600080fd5b61242681600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555080600460008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050565b60008282111515156124bf57fe5b818303905092915050565b6000806124e16001846126b090919063ffffffff16565b9050600061250e612710612500600854856126eb90919063ffffffff16565b61272690919063ffffffff16565b90508092505050919050565b600080828401905083811015151561252e57fe5b8091505092915050565b6000811415151561254857600080fd5b600360008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054811115151561259657600080fd5b6125ab816006546124b190919063ffffffff16565b60068190555061260381600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546124b190919063ffffffff16565b600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b6000806126bd848461251a565b905060006126cc8260016124b1565b90506126e16126db8286612726565b856126eb565b9250505092915050565b6000808314156126fe5760009050612720565b6000828402905082848281151561271157fe5b0414151561271b57fe5b809150505b92915050565b600080828481151561273457fe5b049050809150509291505056fea165627a7a72305820b212ce6500447c96b1cef684e0ba599f36a7be7476701828faca70603724cb2d0029
[ 2 ]
0x5eeb73813f3cdb275e10d9f444843266a8a391a2
pragma solidity 0.5.17; interface IUniswapV2Router02 { function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IERC20FeeProxy { event TransferWithReferenceAndFee( address tokenAddress, address to, uint256 amount, bytes indexed paymentReference, uint256 feeAmount, address feeAddress ); function transferFromWithReferenceAndFee( address _tokenAddress, address _to, uint256 _amount, bytes calldata _paymentReference, uint256 _feeAmount, address _feeAddress ) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract Context { 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(_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 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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeERC20 { /** * @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call. * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value. * @return The return value of the ERC20 call, returning true for non-standard tokens */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool result) { address tokenAddress = address(_token); /* solium-disable security/no-inline-assembly */ // check if the address is a contract assembly { if iszero(extcodesize(tokenAddress)) { revert(0, 0) } } // solium-disable-next-line security/no-low-level-calls (bool success, ) = tokenAddress.call(abi.encodeWithSignature( "transferFrom(address,address,uint256)", _from, _to, _amount )); assembly { switch returndatasize() case 0 { // not a standard erc20 result := 1 } case 32 { // standard erc20 returndatacopy(0, 0, 32) result := mload(0) } default { // anything else, should revert for safety revert(0, 0) } } require(success, "transferFrom() has been reverted"); /* solium-enable security/no-inline-assembly */ return result; } } contract ERC20SwapToPay is Ownable { using SafeERC20 for IERC20; IUniswapV2Router02 public swapRouter; IERC20FeeProxy public paymentProxy; constructor(address _swapRouterAddress, address _paymentProxyAddress) public { swapRouter = IUniswapV2Router02(_swapRouterAddress); paymentProxy = IERC20FeeProxy(_paymentProxyAddress); } /** * @notice Authorizes the proxy to spend a new request currency (ERC20). * @param _erc20Address Address of an ERC20 used as a request currency */ function approvePaymentProxyToSpend(address _erc20Address) public { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.approve(address(paymentProxy), max); } /** * @notice Authorizes the swap router to spend a new payment currency (ERC20). * @param _erc20Address Address of an ERC20 used for payment */ function approveRouterToSpend(address _erc20Address) public { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.approve(address(swapRouter), max); } /** * @notice Performs a token swap between a payment currency and a request currency, and then * calls a payment proxy to pay the request, including fees. * @param _to Transfer recipient = request issuer * @param _amount Amount to transfer in request currency * @param _amountInMax Maximum amount allowed to spend for currency swap, in payment currency. This amount should take into account the fees. @param _path, path of ERC20 tokens to swap from requestedToken to spentToken. The first address of the path should be the payment currency. The last element should be the request currency. * @param _paymentReference Reference of the payment related * @param _feeAmount Amount of the fee in request currency * @param _feeAddress Where to pay the fee * @param _deadline Deadline for the swap to be valid */ function swapTransferWithReference( address _to, uint256 _amount, // requestedToken uint256 _amountInMax, // spentToken address[] calldata _path, // from requestedToken to spentToken bytes calldata _paymentReference, uint256 _feeAmount, // requestedToken address _feeAddress, uint256 _deadline ) external { IERC20 spentToken = IERC20(_path[0]); IERC20 requestedToken = IERC20(_path[_path.length-1]); uint256 requestedTotalAmount = _amount + _feeAmount; require(spentToken.allowance(msg.sender, address(this)) > _amountInMax, "Not sufficient allowance for swap to pay."); require(spentToken.safeTransferFrom(msg.sender, address(this), _amountInMax), "Could not transfer payment token from swapper-payer"); // Allow the router to spend all this contract's spentToken if (spentToken.allowance(address(this),address(swapRouter)) < _amountInMax) { approveRouterToSpend(address(spentToken)); } swapRouter.swapTokensForExactTokens( requestedTotalAmount, _amountInMax, _path, address(this), _deadline ); // Allow the payment network to spend all this contract's requestedToken if (requestedToken.allowance(address(this),address(paymentProxy)) < requestedTotalAmount) { approvePaymentProxyToSpend(address(requestedToken)); } // Pay the request and fees paymentProxy.transferFromWithReferenceAndFee( address(requestedToken), _to, _amount, _paymentReference, _feeAmount, _feeAddress ); // Give the change back to the payer, in both currencies (only spent token should remain) if (spentToken.balanceOf(address(this)) > 0) { spentToken.transfer(msg.sender, spentToken.balanceOf(address(this))); } if (requestedToken.balanceOf(address(this)) > 0) { requestedToken.transfer(msg.sender, requestedToken.balanceOf(address(this))); } } /* * Admin functions to edit the admin, router address or proxy address */ function setPaymentProxy(address _paymentProxyAddress) public onlyOwner { paymentProxy = IERC20FeeProxy(_paymentProxyAddress); } function setRouter(address _newSwapRouterAddress) public onlyOwner { swapRouter = IUniswapV2Router02(_newSwapRouterAddress); } }
0x608060405234801561001057600080fd5b506004361061009e5760003560e01c80638da5cb5b116100665780638da5cb5b146102b6578063a09b241d14610300578063c0d7865514610344578063c31c9c0714610388578063f2fde38b146103d25761009e565b806330e175c9146100a35780633cd3efef146100e7578063715018a6146101315780637262b4c51461013b5780638d09fe2b1461017f575b600080fd5b6100e5600480360360208110156100b957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610416565b005b6100ef61052a565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610139610550565b005b61017d6004803603602081101561015157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506106d8565b005b6102b4600480360361010081101561019657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919080359060200190929190803590602001906401000000008111156101e757600080fd5b8201836020820111156101f957600080fd5b8035906020019184602083028401116401000000008311171561021b57600080fd5b90919293919293908035906020019064010000000081111561023c57600080fd5b82018360208201111561024e57600080fd5b8035906020019184600183028401116401000000008311171561027057600080fd5b909192939192939080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506107e5565b005b6102be611400565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6103426004803603602081101561031657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611429565b005b6103866004803603602081101561035a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061153d565b005b61039061164a565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610414600480360360208110156103e857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611670565b005b600081905060007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff90508173ffffffffffffffffffffffffffffffffffffffff1663095ea7b3600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156104e957600080fd5b505af11580156104fd573d6000803e3d6000fd5b505050506040513d602081101561051357600080fd5b810190808051906020019092919050505050505050565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b61055861187d565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610619576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a360008060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b6106e061187d565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146107a1576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b6000878760008181106107f457fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff1690506000888860018b8b90500381811061082757fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff1690506000858c0190508a8373ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e33306040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b1580156108ff57600080fd5b505afa158015610913573d6000803e3d6000fd5b505050506040513d602081101561092957600080fd5b810190808051906020019092919050505011610990576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526029815260200180611b166029913960400191505060405180910390fd5b6109bd33308d8673ffffffffffffffffffffffffffffffffffffffff16611885909392919063ffffffff16565b610a12576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526033815260200180611b3f6033913960400191505060405180910390fd5b8a8373ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e30600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b158015610ae657600080fd5b505afa158015610afa573d6000803e3d6000fd5b505050506040513d6020811015610b1057600080fd5b81019080805190602001909291905050501015610b3157610b3083610416565b5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638803dbee828d8d8d308a6040518763ffffffff1660e01b815260040180878152602001868152602001806020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018381526020018281038252868682818152602001925060200280828437600081840152601f19601f820116905080830192505050975050505050505050600060405180830381600087803b158015610c2157600080fd5b505af1158015610c35573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052506020811015610c5f57600080fd5b8101908080516040519392919084640100000000821115610c7f57600080fd5b83820191506020820185811115610c9557600080fd5b8251866020820283011164010000000082111715610cb257600080fd5b8083526020830192505050908051906020019060200280838360005b83811015610ce9578082015181840152602081019050610cce565b5050505090500160405250505050808273ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e30600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b158015610dcb57600080fd5b505afa158015610ddf573d6000803e3d6000fd5b505050506040513d6020811015610df557600080fd5b81019080805190602001909291905050501015610e1657610e1582611429565b5b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c219a14d838f8f8c8c8c8c6040518863ffffffff1660e01b8152600401808873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001868152602001806020018481526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281038252868682818152602001925080828437600081840152601f19601f82011690508083019250505098505050505050505050600060405180830381600087803b158015610f6357600080fd5b505af1158015610f77573d6000803e3d6000fd5b5050505060008373ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610ffa57600080fd5b505afa15801561100e573d6000803e3d6000fd5b505050506040513d602081101561102457600080fd5b810190808051906020019092919050505011156111b6578273ffffffffffffffffffffffffffffffffffffffff1663a9059cbb338573ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156110d557600080fd5b505afa1580156110e9573d6000803e3d6000fd5b505050506040513d60208110156110ff57600080fd5b81019080805190602001909291905050506040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561117957600080fd5b505af115801561118d573d6000803e3d6000fd5b505050506040513d60208110156111a357600080fd5b8101908080519060200190929190505050505b60008273ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561123557600080fd5b505afa158015611249573d6000803e3d6000fd5b505050506040513d602081101561125f57600080fd5b810190808051906020019092919050505011156113f1578173ffffffffffffffffffffffffffffffffffffffff1663a9059cbb338473ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561131057600080fd5b505afa158015611324573d6000803e3d6000fd5b505050506040513d602081101561133a57600080fd5b81019080805190602001909291905050506040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156113b457600080fd5b505af11580156113c8573d6000803e3d6000fd5b505050506040513d60208110156113de57600080fd5b8101908080519060200190929190505050505b50505050505050505050505050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b600081905060007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff90508173ffffffffffffffffffffffffffffffffffffffff1663095ea7b3600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16836040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156114fc57600080fd5b505af1158015611510573d6000803e3d6000fd5b505050506040513d602081101561152657600080fd5b810190808051906020019092919050505050505050565b61154561187d565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611606576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b61167861187d565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614611739576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156117bf576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180611af06026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600033905090565b600080859050803b61189657600080fd5b60008173ffffffffffffffffffffffffffffffffffffffff16868686604051602401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200193505050506040516020818303038152906040527f23b872dd000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040518082805190602001908083835b602083106119d857805182526020820191506020810190506020830392506119b5565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611a3a576040519150601f19603f3d011682016040523d82523d6000602084013e611a3f565b606091505b505090503d60008114611a595760208114611a6257600080fd5b60019350611a6e565b60206000803e60005193505b5080611ae2576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f7472616e7366657246726f6d282920686173206265656e20726576657274656481525060200191505060405180910390fd5b829250505094935050505056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734e6f742073756666696369656e7420616c6c6f77616e636520666f72207377617020746f207061792e436f756c64206e6f74207472616e73666572207061796d656e7420746f6b656e2066726f6d20737761707065722d7061796572a265627a7a723158201a3a5a2dbc3df5cfb167f354bceb6b275c0ff783ee8e326541df27f90300ad8664736f6c63430005110032
[ 16, 5 ]
0x5f14e09736f78ba7acb175c3651a5a6bf2d4ce16
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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"); } } library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } 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)); } } library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface ILocker { /** * @dev Returns the locked amount of untransferable tokens of a given `wallet` */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns the locked amount of untransferable and un-delegatable tokens of a given `wallet`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } 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; } library MathUtils { event UnderflowError( uint a, uint b ); uint constant private _EPS = 1e6; function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Can't reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint newValue = sequence.value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value != newValue) { sequence.value = newValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint _i = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len.sub(1); while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; uint constant private _FICTIOUS_MONTH_START = 1599523200; uint constant private _FICTIOUS_MONTH_NUMBER = 9; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); if (timestamp >= _FICTIOUS_MONTH_START) { month = month.add(1); } return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; if (_month > _FICTIOUS_MONTH_NUMBER) { _month = _month.sub(1); } else if (_month == _FICTIOUS_MONTH_NUMBER) { return _FICTIOUS_MONTH_START; } year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * Adds actual contract to mapping of actual contract addresses * @param contractsName - contracts name in skale manager system * @param newContractsAddress - contracts address in skale manager system */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract * @param contractName - human readable name of contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName3))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } contract Punisher is Permissions, ILocker { /** * @dev Emitted when a slashing condition occurs. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted when a forgive condition occurs. */ event Forgive( address wallet, uint amount ); // holder => tokens mapping (address => uint) private _locked; /** * @dev Executes slashing on a validator and its delegations by an `amount` * of tokens. Currently, SkaleDKG is the only service allowed to execute * slashing. * * Emits a Slash event. * * @param validatorId uint validator to be slashed * @param amount uint slashed amount */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Owner to forgive a slashing condition. * * Emits a Forgive event. * * @param holder address of the slashed * @param amount uint amount to be forgiven */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See ILocker-getAndUpdateLockedAmount */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker-getAndUpdateForbiddenForDelegationAmount */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUserCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Can't add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUserCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } function _totalDelegatedSatisfiesProofOfUserCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } contract TokenState is Permissions, ILocker { /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); string[] private _lockers; /** * @dev Return and update the total locked amount of a given `holder`. * * @param holder address of the token holder * @return total locked amount */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint locked = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } /** * @dev Return and update the total locked and un-delegatable amount of a given `holder`. * * @param holder address of the token holder * @return amount total slashed amount (non-transferable and non-delegatable) */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a LockerWasRemoved event. * * @param locker string name of contract to remove from locker */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a LockerWasAdded event. * * @param locker string name of contract to add to locker */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); event ValidatorWasEnabled( uint validatorId ); event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator Id. * * Requirements: * * - sender must not already have registered a validator Id. * - fee rate must be between 0 - 1000‰. Note: per mille! * * Emits ValidatorRegistered event. * * @param name string * @param description string * @param feeRate uint Fee charged on delegations by the validator per mille * @param minimumDelegationAmount uint Minimum delegation amount accepted by the validator */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate < 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the validator whitelist. Once turned off the * whitelist cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows a validator to request a new address. * * Requirements: * * - new address must not be null * - new address must not be already registered as a validator * * @param newValidatorAddress address */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a given node address. * * Requirements: * * - the given signature must be valid. * - the address must not be assigned to a validator. * * Emits NodeAddressWasAdded event. * * @param nodeAddress address * @param sig bytes signature of validator Id by node operator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a given node address from a validator. * * Emits NodeAddressWasRemoved event. * * @param nodeAddress address */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); _removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. * * @param newName string */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. * * @param newDescription string */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - validator must not have already enabled accepting new requests */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - validator must not have already stopped accepting new requests */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } /** * @dev Returns the amount of validator bond. * * @param validatorId uint ID of validator to return the amount of locked funds * @return bondAmount uint the amount of self-delegated funds by the validator */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns a list of trusted validators. * * @return uint[] trusted validators */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } function checkMinimumDelegation(uint validatorId, uint amount) external view checkValidatorExists(validatorId) allow("DelegationController") returns (bool) { return validators[validatorId].minimumDelegationAmount <= amount ? true : false; } function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function isAuthorizedValidator(uint validatorId) external view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator with given address does not exist"); } function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } // private function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _removeNodeAddress(uint validatorId, address nodeAddress) private { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } contract Bounty is Permissions { uint public constant STAGE_LENGTH = 31558150; // 1 year uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant BOUNTY = 96250000 * 1e18; uint private _nextStage; uint private _stagePool; bool public bountyReduction; uint private _nodesPerRewardPeriod; uint private _nodesRemainingPerRewardPeriod; uint private _rewardPeriodFinished; function getBounty( uint nodeIndex, uint downtime, uint latency ) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); _refillStagePool(constantsHolder); if (_rewardPeriodFinished <= now) { _updateNodesPerRewardPeriod(constantsHolder, nodes); } uint bounty = _calculateMaximumBountyAmount(_stagePool, _nextStage, nodeIndex, constantsHolder, nodes); bounty = _reduceBounty( bounty, nodeIndex, downtime, latency, nodes, constantsHolder ); _stagePool = _stagePool.sub(bounty); _nodesRemainingPerRewardPeriod = _nodesRemainingPerRewardPeriod.sub(1); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function calculateNormalBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint stagePoolSize; uint nextStage; (stagePoolSize, nextStage) = _getStagePoolSize(constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, nextStage, nodeIndex, constantsHolder, nodes ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextStage = 0; _stagePool = 0; _rewardPeriodFinished = 0; bountyReduction = false; } // private function _calculateMaximumBountyAmount( uint stagePoolSize, uint nextStage, uint nodeIndex, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } uint numberOfRewards = _getStageBeginningTimestamp(nextStage, constantsHolder) .sub(now) .div(constantsHolder.rewardPeriod()); uint numberOfRewardsPerAllNodes = numberOfRewards.mul(_nodesPerRewardPeriod); return stagePoolSize.div( numberOfRewardsPerAllNodes.add(_nodesRemainingPerRewardPeriod) ); } function _getStageBeginningTimestamp(uint stage, ConstantsHolder constantsHolder) private view returns (uint) { return constantsHolder.launchTimestamp().add(stage.mul(STAGE_LENGTH)); } function _getStagePoolSize(ConstantsHolder constantsHolder) private view returns (uint stagePool, uint nextStage) { stagePool = _stagePool; for (nextStage = _nextStage; now >= _getStageBeginningTimestamp(nextStage, constantsHolder); ++nextStage) { stagePool += _getStageReward(_nextStage); } } function _refillStagePool(ConstantsHolder constantsHolder) private { (_stagePool, _nextStage) = _getStagePoolSize(constantsHolder); } function _updateNodesPerRewardPeriod(ConstantsHolder constantsHolder, Nodes nodes) private { _nodesPerRewardPeriod = nodes.getNumberOnlineNodes(); _nodesRemainingPerRewardPeriod = _nodesPerRewardPeriod; _rewardPeriodFinished = now.add(uint(constantsHolder.rewardPeriod())); } function _getStageReward(uint stage) private pure returns (uint) { if (stage >= 6) { return BOUNTY.div(2 ** stage.sub(6).div(3)); } else { if (stage == 0) { return YEAR1_BOUNTY; } else if (stage == 1) { return YEAR2_BOUNTY; } else if (stage == 2) { return YEAR3_BOUNTY; } else if (stage == 3) { return YEAR4_BOUNTY; } else if (stage == 4) { return YEAR5_BOUNTY; } else { return YEAR6_BOUNTY; } } } function _reduceBounty( uint bounty, uint nodeIndex, uint downtime, uint latency, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = _reduceBountyByDowntime(bounty, nodeIndex, downtime, nodes, constants); if (latency > constants.allowableLatency()) { // reduce bounty because latency is too big reducedBounty = reducedBounty.mul(constants.allowableLatency()).div(latency); } if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _reduceBountyByDowntime( uint bounty, uint nodeIndex, uint downtime, Nodes nodes, ConstantsHolder constants ) private view returns (uint reducedBounty) { reducedBounty = bounty; uint getBountyDeadline = uint(nodes.getNodeLastRewardDate(nodeIndex)) .add(constants.rewardPeriod()) .add(constants.deltaPeriod()); uint numberOfExpiredIntervals; if (now > getBountyDeadline) { numberOfExpiredIntervals = now.sub(getBountyDeadline).div(constants.checkTime()); } else { numberOfExpiredIntervals = 0; } uint normalDowntime = uint(constants.rewardPeriod()) .sub(constants.deltaPeriod()) .div(constants.checkTime()) .div(constants.DOWNTIME_THRESHOLD_PART()); uint totalDowntime = downtime.add(numberOfExpiredIntervals); if (totalDowntime > normalDowntime) { // reduce bounty because downtime is too big uint penalty = bounty .mul(totalDowntime) .div( uint(constants.rewardPeriod()).sub(constants.deltaPeriod()) .div(constants.checkTime()) ); if (bounty > penalty) { reducedBounty = bounty.sub(penalty); } else { reducedBounty = 0; } } } } contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/8 of Node) uint8 public constant MEDIUM_DIVISOR = 8; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 3; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint public firstDelegationsMonth; /** * Set reward and delta periods to new one, run only by owner. This function * only for tests. * @param newRewardPeriod - new Reward period * @param newDeltaPeriod - new Delta period */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * Set new check time. This function only for tests. * @param newCheckTime - new check time */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * Set latency new one in ms, run only by owner. This function * only for tests. * @param newAllowableLatency - new Allowable Latency */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Can't set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setFirstDelegationsMonth(uint month) external onlyOwner { firstDelegationsMonth = month; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 8; } } contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * @param validatorId uint ID of validator to receive delegation proposal * @param amount uint amount of proposed delegation * @param delegationPeriod uint period of proposed delegation * @param info string extra information provided by the token holder (if any) */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); TokenState tokenState = TokenState(contractManager.getContract("TokenState")); require( validatorService.checkMinimumDelegation(validatorId, amount), "Amount does not meet the validator's minimum delegation amount"); require( validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require( delegationPeriodManager.isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); require( validatorService.isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = skaleToken.balanceOf(msg.sender); uint forbiddenForDelegation = tokenState.getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See ILocker. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows a token holder to cancel a delegation proposal. * * Requirements: * * - the sender must be the token holder of the delegation proposal. * - the delegation must still be in a PROPOSED state. * * Emits a DelegationRequestCanceledByUser event. * * @param delegationId uint ID of delegation proposal */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a DelegationAccepted event. * * @param delegationId uint ID of delegation proposal */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( validatorService.checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); tokenLaunchLocker.handleDelegationAdd( delegations[delegationId].holder, delegationId, delegations[delegationId].amount, delegations[delegationId].started); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } /** * @dev Allows a delegator to undelegate a specific delegation. * * Requirements: * * - the sender must be the delegator. * - the delegation must be in DELEGATED state. * * Emits an UndelegationRequested event. * * @param delegationId uint ID of delegation to undelegate */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); tokenLaunchLocker.handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); emit UndelegationRequested(delegationId); } /** * @dev Allows the Punisher to confiscate an `amount` of stake from * `validatorId` by slashing. This slashes all delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manger to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * See Punisher. * * Emits a SlashingEvent. * * @param validatorId uint validator to slash * @param amount uint amount to slash * */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); } function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allow("Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function getAndUpdateDelegatedToValidator(uint validatorId, uint month) public allow("Nodes") returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. * * @param delegationId uint ID of the delegation */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); if (_getCurrentMonth() == timeHelpers.timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); require( _lockedInPendingDelegations[holder].month == currentMonth, "There are no delegation requests this month"); require(_lockedInPendingDelegations[holder].amount >= amount, "Unlocking amount is too big"); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); return timeHelpers.getCurrentMonth(); } function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getContract("Punisher")); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < constantsHolder.limitValidatorsPerDelegator() ), "Limit of validators is reached" ); require( _getCurrentMonth() >= constantsHolder.firstDelegationsMonth(), "Delegations are not allowed" ); } } contract DelegationPeriodManager is Permissions { /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); mapping (uint => uint) public stakeMultipliers; /** * @dev Creates a new available delegation period and return in the network. * Only the owner may set new delegation period and returns in the network. * * Emits a DelegationPeriodWasSet event. * * @param monthsCount uint delegation duration in months * @param stakeMultiplier uint return for delegation */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. * * @param monthsCount uint delegation duration in months * @return bool True if delegation period is allowed */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0 ? true : false; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[3] = 100; // 3 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; // informs that Node is created event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint time, uint gasSpend ); // informs that node is fully finished quitting from the system event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); // informs that owner starts the procedure of quitting the Node from the system event ExitInited( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } /** * @dev removeSpaceFromFractionalNode - occupies space from Fractional Node * function could be run only by Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be occupied */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev adSpaceToFractionalNode - returns space to Fractional Node * function could be run only be Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be returned */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev changeNodeLastRewardDate - changes Node's last reward date * function could be run only by SkaleManager * @param nodeIndex - index of Node */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev createNode - creates new Node and add it to the Nodes contract * function could be only run by SkaleManager * @param from - owner of Node */ // * @return nodeIndex - index of Node function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name has already registered"); require(params.port > 0, "Port is zero"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, block.timestamp, gasleft()); } /** * @dev initExit - initiate a procedure of quitting the system * function could be only run by SkaleManager * @param nodeIndex - index of Node * @return true - if everything OK */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { _setNodeLeaving(nodeIndex); emit ExitInited( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev completeExit - finish a procedure of quitting the system * function could be run only by SkaleManager * @param nodeIndex - index of Node * @return amount of SKL which be returned */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); } function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function setNodeInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.In_Maintenance; } function removeNodeFromInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintence"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.Active; } function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev isTimeForReward - checks if time for reward has come * @param nodeIndex - index of Node * @return if time for reward has come - true, else - false */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return uint(nodes[nodeIndex].lastRewardDate).add(constantsHolder.rewardPeriod()) <= block.timestamp; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev getNodePort - get Node's port * @param nodeIndex - index of Node * @return port */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev isNodeLeft - checks if Node status Left * @param nodeIndex - index of Node * @return if Node status Left - true, else - false */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev getNodeNextRewardDate - get Node next reward date * @param nodeIndex - index of Node * @return Node next reward date */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes[nodeIndex].lastRewardDate.add(constantsHolder.rewardPeriod()); } /** * @dev getNumberOfNodes - get number of Nodes * @return number of Nodes */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev getNumberOfFullNodes - get number Online Nodes * @return number of active nodes plus number of leaving nodes */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev getActiveNodeIPs - get array of ips of Active Nodes * @return activeNodeIPs - array of ips of Active Nodes */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev getActiveNodesByAddress - get array of indexes of Active Nodes, which were * created by msg.sender * @return activeNodesByAddress Array of indexes of Active Nodes, which were created by msg.sender */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev getActiveNodeIds - get array of indexes of Active Nodes * @return activeNodeIds - array of indexes of Active Nodes */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev isNodeExist - checks existence of Node at this address * @param from - account address * @param nodeIndex - index of Node * @return if exist - true, else - false */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev isNodeActive - checks if Node status Active * @param nodeIndex - index of Node * @return if Node status Active - true, else - false */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev isNodeLeaving - checks if Node status Leaving * @param nodeIndex - index of Node * @return if Node status Leaving - true, else - false */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev _setNodeLeft - set Node Left * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev _setNodeLeaving - set Node Leaving * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev _addNode - adds Node to array * function could be run only by executor * @param from - owner of Node * @param name - Node name * @param ip - Node ip * @param publicIP - Node public ip * @param port - Node public port * @param publicKey - Ethereum public key * @return nodeIndex Index of Node */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } }
0x608060405234801561001057600080fd5b506004361061007d5760003560e01c80638da5cb5b1161005b5780638da5cb5b14610120578063dd9e294014610128578063ec56a373146101a1578063f2fde38b146101be5761007d565b80633581777314610082578063715018a61461010e5780638129fc1c14610118575b600080fd5b6100f26004803603602081101561009857600080fd5b8101906020810181356401000000008111156100b357600080fd5b8201836020820111156100c557600080fd5b803590602001918460018302840111640100000000831117156100e757600080fd5b5090925090506101e4565b604080516001600160a01b039092168252519081900360200190f35b61011661033f565b005b6101166103f3565b6100f261049d565b6101166004803603604081101561013e57600080fd5b81019060208101813564010000000081111561015957600080fd5b82018360208201111561016b57600080fd5b8035906020019184600183028401116401000000008311171561018d57600080fd5b9193509150356001600160a01b03166104ac565b6100f2600480360360208110156101b757600080fd5b50356106f9565b610116600480360360208110156101d457600080fd5b50356001600160a01b0316610714565b6000609760008484604051602001808383808284376040805191909301818103601f1901825283528051602091820120875286810197909752509384016000205484518086018652601c81527f20636f6e747261637420686173206e6f74206265656e20666f756e6400000000818801528551601f8a018890048802810188019096528886526001600160a01b039091169650861515956102af95919450909250889150879081908401838280828437600092019190915250929392505063ffffffff61081f169050565b906103385760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156102fd5781810151838201526020016102e5565b50505050905090810190601f16801561032a5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5092915050565b610347610937565b6065546001600160a01b039081169116146103a9576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6065546040516000916001600160a01b0316907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908390a3606580546001600160a01b0319169055565b600054610100900460ff168061040c575061040c61093b565b8061041a575060005460ff16155b6104555760405162461bcd60e51b815260040180806020018281038252602e815260200180610c68602e913960400191505060405180910390fd5b600054610100900460ff16158015610480576000805460ff1961ff0019909116610100171660011790555b610488610941565b801561049a576000805461ff00191690555b50565b6065546001600160a01b031690565b6104b4610937565b6065546001600160a01b03908116911614610516576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b038116610571576040805162461bcd60e51b815260206004820152601960248201527f4e6577206164647265737320697320657175616c207a65726f00000000000000604482015290519081900360640190fd5b60008383604051602001808383808284376040805191909301818103601f19018252835280516020918201206000818152609790925292902054919550506001600160a01b03868116911614159250610614915050576040805162461bcd60e51b815260206004820152601960248201527f436f6e747261637420697320616c726561647920616464656400000000000000604482015290519081900360640190fd5b610626826001600160a01b03166109de565b6106615760405162461bcd60e51b815260040180806020018281038252602d815260200180610c15602d913960400191505060405180910390fd5b60008181526097602090815260409182902080546001600160a01b0319166001600160a01b0386169081179091558251918201528181529081018490527f2b51ff7c4cc8e6fe1c72e9d9685b7d2a88a5d82ad3a644afbdceb0272c89c1c3908590859085908060608101858580828437600083820152604051601f909101601f1916909201829003965090945050505050a150505050565b6097602052600090815260409020546001600160a01b031681565b61071c610937565b6065546001600160a01b0390811691161461077e576040805162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015290519081900360640190fd5b6001600160a01b0381166107c35760405162461bcd60e51b8152600401808060200182810382526026815260200180610c426026913960400191505060405180910390fd5b6065546040516001600160a01b038084169216907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a3606580546001600160a01b0319166001600160a01b0392909216919091179055565b8051825160609184918491849161083b9163ffffffff610a1a16565b67ffffffffffffffff8111801561085157600080fd5b506040519080825280601f01601f19166020018201604052801561087c576020820181803683370190505b509050806000805b85518110156108d55785818151811061089957fe5b602001015160f81c60f81b8383806001019450815181106108b657fe5b60200101906001600160f81b031916908160001a905350600101610884565b5060005b845181101561092a578481815181106108ee57fe5b602001015160f81c60f81b83838060010194508151811061090b57fe5b60200101906001600160f81b031916908160001a9053506001016108d9565b5090979650505050505050565b3390565b303b1590565b600054610100900460ff168061095a575061095a61093b565b80610968575060005460ff16155b6109a35760405162461bcd60e51b815260040180806020018281038252602e815260200180610c68602e913960400191505060405180910390fd5b600054610100900460ff161580156109ce576000805460ff1961ff0019909116610100171660011790555b6109d6610a7b565b610488610b1b565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590610a1257508115155b949350505050565b600082820183811015610a74576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b600054610100900460ff1680610a945750610a9461093b565b80610aa2575060005460ff16155b610add5760405162461bcd60e51b815260040180806020018281038252602e815260200180610c68602e913960400191505060405180910390fd5b600054610100900460ff16158015610488576000805460ff1961ff001990911661010017166001179055801561049a576000805461ff001916905550565b600054610100900460ff1680610b345750610b3461093b565b80610b42575060005460ff16155b610b7d5760405162461bcd60e51b815260040180806020018281038252602e815260200180610c68602e913960400191505060405180910390fd5b600054610100900460ff16158015610ba8576000805460ff1961ff0019909116610100171660011790555b6000610bb2610937565b606580546001600160a01b0319166001600160a01b038316908117909155604051919250906000907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0908290a350801561049a576000805461ff00191690555056fe476976656e20636f6e747261637473206164647265737320646f6573206e6f7420636f6e7461696e20636f64654f776e61626c653a206e6577206f776e657220697320746865207a65726f2061646472657373436f6e747261637420696e7374616e63652068617320616c7265616479206265656e20696e697469616c697a6564a264697066735822122080b3b6fe9d056a3b675cade4cebd6804619de33e563bf065814ff3396dff589564736f6c634300060a0033
[ 6, 4, 9, 7 ]
0x5f906a6af3f5d52dc84e0e472e95501f24ebaef0
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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"); } } library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } 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)); } } library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - (subtracted.a), p); } else { difference.a = p - (addmod(subtracted.a, p - (diminished.a), p)); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - (subtracted.b), p); } else { difference.b = p - (addmod(subtracted.b, p - (diminished.b), p)); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = p - addmod(t2, p - t0, p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = p - mulmod(value.b, t3, p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG1() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = p - sum.y.a; sum.y.b = p - sum.y.b; } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = p - result.y.a; result.y.b = p - result.y.b; } } } library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } 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; } library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint newValue = sequence.value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value != newValue) { sequence.value = newValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint _i = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len.sub(1); while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getTokenLaunchLocker() external view returns (address) { return getContract(TOKEN_LAUNCH_LOCKER); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); _addSchain(msg.sender, 0, schainParameters); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Returns the number of Nodes and resource divisor that is needed for a * given Schain type. */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { revert("Bad schain type"); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { uint numberOfNodes; uint8 partOfNode; require(schainParameters.typeOfSchain <= 5, "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } contract SchainsInternal is Permissions { struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainId = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainId); } function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].pop(); } } } function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) { return schains[schainId].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainId) external view returns (address) { return schains[schainId].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId]; } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); } else { schainsForNodes[nodeIndex][holesForNodes[nodeIndex][0]] = schainId; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForNodes[nodeIndex].length; i++) { if (min > holesForNodes[nodeIndex][i]) { min = holesForNodes[nodeIndex][i]; index = i; } } if (min == uint(-1)) { delete holesForNodes[nodeIndex]; } else { holesForNodes[nodeIndex][0] = min; holesForNodes[nodeIndex][index] = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; holesForNodes[nodeIndex].pop(); } } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) public view returns (uint) { return schainsForNodes[nodeIndex].length; } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { uint length = getLengthOfSchainsForNode(nodeIndex); for (uint i = 0; i < length; i++) { if (schainsForNodes[nodeIndex][i] == schainId) { return i; } } return length; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } /** * @dev Swaps one index for another in an array. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); event BountyGot( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce}); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); bool completed; bool isSchains = false; if (schainsInternal.getActiveSchain(nodeIndex) != bytes32(0)) { completed = nodeRotation.exitFromSchain(nodeIndex); isSchains = true; } else { completed = true; } if (completed) { require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime(nodeIndex, now.add(isSchains ? constants.rotationDelay() : 0)); // Monitors monitors = Monitors(contractManager.getContract("Monitors")); // monitors.removeCheckedNodes(nodeIndex); // monitors.deleteMonitor(nodeIndex); nodes.deleteNodeForValidator(validatorId, nodeIndex); } } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require( nodes.isNodeActive(nodeIndex) || nodes.isNodeLeaving(nodeIndex), "Node is not Active and is not Leaving" ); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); if (bounty > 0) { _payBounty(bounty, nodes.getValidatorId(nodeIndex)); } _emitBountyEvent(nodeIndex, msg.sender, 0, 0, bounty); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _emitBountyEvent( uint nodeIndex, address from, uint averageDowntime, uint averageLatency, uint bounty ) private { Monitors monitors = Monitors(contractManager.getContract("Monitors")); uint previousBlockEvent = monitors.getLastBountyBlock(nodeIndex); monitors.setLastBountyBlock(nodeIndex); emit BountyReceived( nodeIndex, from, averageDowntime, averageLatency, bounty, previousBlockEvent, block.timestamp, gasleft()); emit BountyGot( nodeIndex, from, averageDowntime, averageLatency, bounty, previousBlockEvent, block.timestamp, gasleft()); } } contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB; if (!(signature.a == 0 && signature.b == 0)) { newSignB = Fp2Operations.P.sub((signature.b % Fp2Operations.P)); } else { newSignB = signature.b; } require(G2Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G2Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; /** * @dev Allows TokenLaunchManager contract to lock an amount of tokens in a * holder wallet. * * Emits a {Locked} event. */ function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new delegations. */ function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new undelegation requests. */ function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev Returns and updates the current delegated amount. */ function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } /** * @dev Adds a delegated amount to the given month. */ function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } /** * @dev Removes a delegated amount from the given month. */ function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } /** * @dev Adds the amount to the total delegated for the given month. */ function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Cannot add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } /** * @dev Unlocks tokens. * * Emits an {Unlocked} event. */ function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } /** * @dev Deletes the delegated amount. */ function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } /** * @dev Deletes the total delegated amount. */ function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } /** * @dev Checks whether total delegated satisfies Proof-of-Use. */ function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } contract TokenState is Permissions, ILocker { string[] private _lockers; /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint locked = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); uint bounty = _calculateMaximumBountyAmount(_epochPool, currentMonth, nodeIndex, constantsHolder, nodes); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint validatorId, uint amount, uint month ) external allow("DelegationController") { if (nodesByValidator[validatorId] > 0) { _effectiveDelegatedSum.addToValue(amount.mul(nodesByValidator[validatorId]), month); } } function handleDelegationRemoving( uint validatorId, uint amount, uint month ) external allow("DelegationController") { if (nodesByValidator[validatorId] > 0) { _effectiveDelegatedSum.subtractFromValue(amount.mul(nodesByValidator[validatorId]), month); } } function handleNodeCreation(uint validatorId) external allow("Nodes") { nodesByValidator[validatorId] = nodesByValidator[validatorId].add(1); _changeEffectiveDelegatedSum(validatorId, true); } function handleNodeRemoving(uint validatorId) external allow("Nodes") { require(nodesByValidator[validatorId] > 0, "All nodes have been already removed"); nodesByValidator[validatorId] = nodesByValidator[validatorId].sub(1); _changeEffectiveDelegatedSum(validatorId, false); } function estimateBounty(uint /* nodeIndex */) external pure returns (uint) { revert("Not implemented"); // ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); // Nodes nodes = Nodes(contractManager.getContract("Nodes")); // TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); // uint stagePoolSize; // uint nextStage; // (stagePoolSize, nextStage) = _getEpochPool(timeHelpers.getCurrentMonth(), timeHelpers, constantsHolder); // return _calculateMaximumBountyAmount( // stagePoolSize, // nextStage.sub(1), // nodeIndex, // constantsHolder, // nodes // ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint currentMonth, uint nodeIndex, ConstantsHolder constantsHolder, Nodes nodes ) private returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } uint effectiveDelegatedSum = _effectiveDelegatedSum.getAndUpdateValue(currentMonth); if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController")); return epochPoolSize .add(_bountyWasPaidInCurrentEpoch) .mul( delegationController.getAndUpdateEffectiveDelegatedToValidator( nodes.getValidatorId(nodeIndex), currentMonth ) ) .div(effectiveDelegatedSum); } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _changeEffectiveDelegatedSum(uint validatorId, bool add) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController(contractManager.getContract("DelegationController")); uint currentMonth = timeHelpers.getCurrentMonth(); uint current = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(current == effectiveDelegated[0]); uint addedToStatistic = 0; bool addToCurrentMonth = now < timeHelpers.monthToTimestamp(currentMonth).add(nodeCreationWindowSeconds); for (uint i = 0; i < _max(effectiveDelegated.length, 2); ++i) { if (i > 0 || addToCurrentMonth) { uint _effectiveDelegated; if (i < effectiveDelegated.length) { _effectiveDelegated = effectiveDelegated[i]; } else { _effectiveDelegated = effectiveDelegated[effectiveDelegated.length.sub(1)]; } if (_effectiveDelegated != addedToStatistic) { _addToEffectiveDelegatedSum(currentMonth.add(i), _effectiveDelegated, addedToStatistic, add); addedToStatistic = _effectiveDelegated; } } } } } function _addToEffectiveDelegatedSum(uint month, uint newValue, uint oldValue, bool add) private { if (newValue > oldValue) { uint diff = newValue.sub(oldValue); if (add) { _effectiveDelegatedSum.addToValue(diff, month); } else { _effectiveDelegatedSum.subtractFromValue(diff, month); } } else if (newValue < oldValue) { uint diff = oldValue.sub(newValue); if (add) { _effectiveDelegatedSum.subtractFromValue(diff, month); } else { _effectiveDelegatedSum.addToValue(diff, month); } } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/8 of Node) uint8 public constant MEDIUM_DIVISOR = 8; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; _getTokenLaunchLocker().handleDelegationAdd( delegations[delegationId].holder, delegationId, amount, delegations[delegationId].started ); uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getTokenLaunchLocker().handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( validatorId, initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( validatorId, initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function getAndUpdateDelegatedToValidator(uint validatorId, uint month) public allow("Nodes") returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); require( _lockedInPendingDelegations[holder].month == currentMonth, "There are no delegation requests this month"); require(_lockedInPendingDelegations[holder].amount >= amount, "Unlocking amount is too big"); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) { return TokenLaunchLocker(contractManager.getTokenLaunchLocker()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } } contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } contract Monitors is Permissions { using StringUtils for string; using SafeCast for uint; struct Verdict { uint toNodeIndex; uint32 downtime; uint32 latency; } struct CheckedNode { uint nodeIndex; uint time; } struct CheckedNodeWithIp { uint nodeIndex; uint time; bytes4 ip; } mapping (bytes32 => CheckedNode[]) public checkedNodes; mapping (bytes32 => uint[][]) public verdicts; mapping (bytes32 => uint[]) public groupsForMonitors; mapping (bytes32 => uint) public lastVerdictBlocks; mapping (bytes32 => uint) public lastBountyBlocks; /** * @dev Emitted when a monitor group is created. */ event MonitorCreated( uint nodeIndex, bytes32 monitorIndex, uint numberOfMonitors, uint[] nodesInGroup, uint time, uint gasSpend ); /** * @dev Emitted when a verdict is sent. */ event VerdictSent( uint indexed fromMonitorIndex, uint indexed toNodeIndex, uint32 downtime, uint32 latency, bool status, uint previousBlockEvent, uint time, uint gasSpend ); /** * @dev Emitted when metrics are calculated. */ event MetricsCalculated( uint forNodeIndex, uint32 averageDowntime, uint32 averageLatency, uint time, uint gasSpend ); /** * @dev Emitted when monitoring periods are set. */ event PeriodsSet( uint rewardPeriod, uint deltaPeriod, uint time, uint gasSpend ); /** * @dev Emitted when node rotation in a monitor group is performed. */ event MonitorRotated( bytes32 monitorIndex, uint newNode ); /** * @dev Allows SkaleManager contract to create a monitoring group. * * Emits a {MonitorCreated} event. */ function addMonitor(uint nodeIndex) external allow("SkaleManager") { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); _generateGroup(monitorIndex, nodeIndex, constantsHolder.NUMBER_OF_MONITORS()); CheckedNode memory checkedNode = _getCheckedNodeData(nodeIndex); for (uint i = 0; i < groupsForMonitors[monitorIndex].length; i++) { bytes32 index = keccak256(abi.encodePacked(groupsForMonitors[monitorIndex][i])); addCheckedNode(index, checkedNode); } emit MonitorCreated( nodeIndex, monitorIndex, groupsForMonitors[monitorIndex].length, groupsForMonitors[monitorIndex], block.timestamp, gasleft() ); } /** * @dev Allows SkaleManager contract to delete a monitoring group. */ function deleteMonitor(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); while (verdicts[keccak256(abi.encodePacked(nodeIndex))].length > 0) { verdicts[keccak256(abi.encodePacked(nodeIndex))].pop(); } uint[] memory nodesInGroup = groupsForMonitors[monitorIndex]; uint index; bytes32 monitoringIndex; for (uint i = 0; i < nodesInGroup.length; i++) { monitoringIndex = keccak256(abi.encodePacked(nodesInGroup[i])); (index, ) = _find(monitoringIndex, nodeIndex); if (index < checkedNodes[monitoringIndex].length) { if (index != checkedNodes[monitoringIndex].length.sub(1)) { checkedNodes[monitoringIndex][index] = checkedNodes[monitoringIndex][checkedNodes[monitoringIndex].length.sub(1)]; } checkedNodes[monitoringIndex].pop(); } } delete groupsForMonitors[monitorIndex]; } /** * @dev Allows SkaleManager contract to remove nodes from a monitoring list. */ function removeCheckedNodes(uint nodeIndex) external allow("SkaleManager") { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); delete checkedNodes[monitorIndex]; } /** * @dev Allows SkaleManager contract to send a monitoring verdict. * * Emits a {VerdictSent} event. * * Requirements: * * - Node must exist in the monitor group. */ function sendVerdict(uint fromMonitorIndex, Verdict calldata verdict) external allow("SkaleManager") { uint index; uint time; bytes32 monitorIndex = keccak256(abi.encodePacked(fromMonitorIndex)); (index, time) = _find(monitorIndex, verdict.toNodeIndex); require(time > 0, "Checked Node does not exist in MonitorsArray"); if (time <= block.timestamp) { if (index != checkedNodes[monitorIndex].length.sub(1)) { checkedNodes[monitorIndex][index] = checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; } delete checkedNodes[monitorIndex][checkedNodes[monitorIndex].length.sub(1)]; checkedNodes[monitorIndex].pop(); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); bool receiveVerdict = time.add(constantsHolder.deltaPeriod()) > block.timestamp; if (receiveVerdict) { verdicts[keccak256(abi.encodePacked(verdict.toNodeIndex))].push( [uint(verdict.downtime), uint(verdict.latency)] ); } _emitVerdictsEvent(fromMonitorIndex, verdict, receiveVerdict); } } /** * @dev Allows SkaleManager contract to calculate median statistics of downtime * and latency. */ function calculateMetrics(uint nodeIndex) external allow("SkaleManager") returns (uint averageDowntime, uint averageLatency) { bytes32 monitorIndex = keccak256(abi.encodePacked(nodeIndex)); uint lengthOfArray = getLengthOfMetrics(monitorIndex); uint[] memory downtimeArray = new uint[](lengthOfArray); uint[] memory latencyArray = new uint[](lengthOfArray); for (uint i = 0; i < lengthOfArray; i++) { downtimeArray[i] = verdicts[monitorIndex][i][0]; latencyArray[i] = verdicts[monitorIndex][i][1]; } if (lengthOfArray > 0) { averageDowntime = _median(downtimeArray); averageLatency = _median(latencyArray); } delete verdicts[monitorIndex]; } /** * @dev Allows SkaleManager contract to set a node's last bounty block. */ function setLastBountyBlock(uint nodeIndex) external allow("SkaleManager") { lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))] = block.number; } /** * @dev Returns node info of nodes in a monitoring list. * Node info includes IPs, nodeIndex, and time to send verdict. * */ function getCheckedArray(bytes32 monitorIndex) external view returns (CheckedNodeWithIp[] memory checkedNodesWithIp) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNodesWithIp = new CheckedNodeWithIp[](checkedNodes[monitorIndex].length); for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { checkedNodesWithIp[i].nodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodesWithIp[i].time = checkedNodes[monitorIndex][i].time; checkedNodesWithIp[i].ip = nodes.getNodeIP(checkedNodes[monitorIndex][i].nodeIndex); } } /** * @dev Returns the latest blocknumber when node received bounty. */ function getLastBountyBlock(uint nodeIndex) external view returns (uint) { return lastBountyBlocks[keccak256(abi.encodePacked(nodeIndex))]; } /** * @dev Returns the nodes in a monitoring group. */ function getNodesInGroup(bytes32 monitorIndex) external view returns (uint[] memory) { return groupsForMonitors[monitorIndex]; } /** * @dev Returns the number of nodes in a monitoring group. */ function getNumberOfNodesInGroup(bytes32 monitorIndex) external view returns (uint) { return groupsForMonitors[monitorIndex].length; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleManager contract to add checked node or update existing * one if it is already exits. */ function addCheckedNode(bytes32 monitorIndex, CheckedNode memory checkedNode) public allow("SkaleManager") { for (uint i = 0; i < checkedNodes[monitorIndex].length; ++i) { if (checkedNodes[monitorIndex][i].nodeIndex == checkedNode.nodeIndex) { checkedNodes[monitorIndex][i] = checkedNode; return; } } checkedNodes[monitorIndex].push(checkedNode); } /** * @dev Returns the blocknumber when a node received its latest verdict. */ function getLastReceivedVerdictBlock(uint nodeIndex) public view returns (uint) { return lastVerdictBlocks[keccak256(abi.encodePacked(nodeIndex))]; } /** * @dev Returns a count of metric data available for a node. */ function getLengthOfMetrics(bytes32 monitorIndex) public view returns (uint) { return verdicts[monitorIndex].length; } /** * @dev Generates a monitoring group, using a pseudo-random number generator. */ function _generateGroup(bytes32 monitorIndex, uint nodeIndex, uint numberOfNodes) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint[] memory activeNodes = nodes.getActiveNodeIds(); uint numberOfNodesInGroup; uint availableAmount = activeNodes.length.sub((nodes.isNodeActive(nodeIndex)) ? 1 : 0); if (numberOfNodes > availableAmount) { numberOfNodesInGroup = availableAmount; } else { numberOfNodesInGroup = numberOfNodes; } uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), monitorIndex))); for (uint i = 0; i < numberOfNodesInGroup; ++i) { uint index = random % (activeNodes.length.sub(ignoringTail)); if (activeNodes[index] == nodeIndex) { _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; index = random % (activeNodes.length.sub(ignoringTail)); } groupsForMonitors[monitorIndex].push(activeNodes[index]); _swap(activeNodes, index, activeNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; } } /** * @dev Returns the median using the Quicksort algorithm. */ function _median(uint[] memory values) private pure returns (uint) { require(values.length > 0, "Cannot calculate _median of an empty array"); _quickSort(values, 0, values.length.sub(1)); return values[values.length.div(2)]; } /** * @dev Performs swap functions for monitoring group generation. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Performs find functions for monitoring indexes. */ function _find(bytes32 monitorIndex, uint nodeIndex) private view returns (uint index, uint time) { index = checkedNodes[monitorIndex].length; time = 0; for (uint i = 0; i < checkedNodes[monitorIndex].length; i++) { uint checkedNodeNodeIndex; uint checkedNodeTime; checkedNodeNodeIndex = checkedNodes[monitorIndex][i].nodeIndex; checkedNodeTime = checkedNodes[monitorIndex][i].time; if (checkedNodeNodeIndex == nodeIndex && (time == 0 || checkedNodeTime < time)) { index = i; time = checkedNodeTime; } } } /** * @dev Performs Quicksort. */ function _quickSort(uint[] memory array, uint left, uint right) private pure { uint leftIndex = left; uint rightIndex = right; uint middle = array[right.add(left).div(2)]; while (leftIndex <= rightIndex) { while (array[leftIndex] < middle) { leftIndex++; } while (middle < array[rightIndex]) { rightIndex--; } if (leftIndex <= rightIndex) { (array[leftIndex], array[rightIndex]) = (array[rightIndex], array[leftIndex]); leftIndex++; rightIndex = (rightIndex > 0 ? rightIndex.sub(1) : 0); } } if (left < rightIndex) _quickSort(array, left, rightIndex); if (leftIndex < right) _quickSort(array, leftIndex, right); } /** * @dev Returns monitoring data for a node. */ function _getCheckedNodeData(uint nodeIndex) private view returns (CheckedNode memory checkedNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); checkedNode.nodeIndex = nodeIndex; checkedNode.time = nodes.getNodeLastRewardDate(nodeIndex) .add(constantsHolder.rewardPeriod()) .sub(constantsHolder.deltaPeriod()); } /** * @dev Performs emission of VerdictSent. * * Emits a {VerdictSent} event. */ function _emitVerdictsEvent( uint fromMonitorIndex, Verdict memory verdict, bool receiveVerdict ) private { uint previousBlockEvent = getLastReceivedVerdictBlock(verdict.toNodeIndex); lastVerdictBlocks[keccak256(abi.encodePacked(verdict.toNodeIndex))] = block.number; emit VerdictSent( fromMonitorIndex, verdict.toNodeIndex, verdict.downtime, verdict.latency, receiveVerdict, previousBlockEvent, block.timestamp, gasleft() ); } } contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No free Nodes available for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str()); string memory dkgRevert = "DKG process did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyOwner { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No free Nodes available for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); BountyV2(contractManager.getBounty()).handleNodeRemoving(nodes[nodeIndex].validatorId); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isAdmin(msg.sender) || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isAdmin(msg.sender) || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); _setNodeActive(nodeIndex); } function populateBountyV2(uint from, uint to) external onlyOwner { BountyV2 bounty = BountyV2(contractManager.getBounty()); uint nodeCreationWindow = bounty.nodeCreationWindowSeconds(); bounty.setNodeCreationWindowSeconds(uint(-1) / 2); for (uint nodeId = from; nodeId < _min(nodes.length, to); ++nodeId) { if (nodes[nodeId].status != NodeStatus.Left) { bounty.handleNodeCreation(nodes[nodeId].validatorId); } } bounty.setNodeCreationWindowSeconds(nodeCreationWindow); } /** * @dev Returns nodes with space availability. */ function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Returns IPs of active nodes. */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev Returns active nodes linked to the `msg.sender` (validator address). */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev Adds node to array. */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; BountyV2(contractManager.getBounty()).handleNodeCreation(validatorId); } /** * @dev Deletes node from array. */ function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } }
0x608060405234801561001057600080fd5b506004361061025e5760003560e01c806391d1485411610146578063ca8df720116100c3578063d6832ea911610087578063d6832ea914610545578063d6b0f4841461054d578063dff0769714610555578063e630025a14610568578063ee7d3cad14610570578063f93c86f1146105785761025e565b8063ca8df720146104e4578063d2ae2c34146104f7578063d3f3872e14610517578063d547741f1461051f578063d55d6f4d146105325761025e565b8063bad217751161010a578063bad2177514610483578063bed5012e14610496578063c10c16eb146104a9578063c4d66de8146104be578063ca15c873146104d15761025e565b806391d148541461042d578063a217fddf14610440578063ab6f878414610448578063b39e12cf1461045b578063b5d89627146104635761025e565b8063365f6f27116101df57806374760abf116101a357806374760abf146103ae578063790ac49b146103c1578063895d6019146103d45780638c34de7e146103e75780638f5683b3146103fa5780639010d07c1461040d5761025e565b8063365f6f271461034f57806348b432a714610362578063549eb4bb146103755780635be8c60f14610388578063665cdf8c1461039b5761025e565b806328f89d7d1161022657806328f89d7d146102e75780632f2ff15d146102ef57806331effd601461030257806335aa2e441461031557806336568abe1461033c5761025e565b806312220f8014610263578063174e68321461028c5780631806a46c146102ac5780632010ba31146102c1578063248a9ca3146102d4575b600080fd5b6102766102713660046126bb565b61058b565b6040516102839190612a44565b60405180910390f35b61029f61029a3660046126bb565b6105ac565b6040516102839190612989565b6102bf6102ba3660046127a9565b6105d3565b005b6102bf6102cf3660046126bb565b610949565b61029f6102e2366004612791565b6109e3565b6102bf6109f8565b6102bf6102fd3660046127a9565b610a45565b61029f610310366004612839565b610a8d565b610328610323366004612791565b610c88565b604051610283989796959493929190612a97565b6102bf61034a3660046127a9565b610df4565b6102bf61035d3660046126bb565b610e36565b6102bf6103703660046127d8565b610ed8565b6102bf610383366004612791565b610f53565b610276610396366004612791565b6110e4565b6102bf6103a93660046126bb565b6110fd565b6102bf6103bc3660046127f9565b611125565b6102bf6103cf366004612791565b611155565b6102bf6103e23660046126f3565b61124d565b6102766103f5366004612791565b61137e565b6102bf6104083660046127f9565b6113c0565b61042061041b3660046127d8565b6113e7565b6040516102839190612992565b61027661043b3660046127a9565b61140c565b61029f61142a565b6102bf610456366004612791565b61142f565b610420611452565b610476610471366004612791565b611461565b604051610283919061343d565b61029f6104913660046126bb565b611626565b6102766104a4366004612746565b61165c565b6104b161167d565b6040516102839190612a0c565b6102bf6104cc3660046126bb565b6116d6565b61029f6104df366004612791565b61176f565b61029f6104f2366004612791565b611786565b61050a610505366004612791565b611897565b60405161028391906129bf565b6102bf611903565b6102bf61052d3660046127a9565b611954565b61029f610540366004612791565b61198e565b61029f6119ac565b6102bf6119b2565b6102bf610563366004612791565b6119e2565b610276611ab2565b61050a611abb565b610276610586366004612791565b611ace565b6001600160a01b0381166000908152609b602052604090205415155b919050565b60006105b7826110fd565b506001600160a01b03166000908152609b602052604090205490565b604080518082018252601081526f56616c696461746f725365727669636560801b6020808301919091528251808401845260058152644e6f64657360d81b918101919091526097549251633581777360e01b81529192909133916001600160a01b03169063358177739061064b908690600401612a84565b60206040518083038186803b15801561066357600080fd5b505afa158015610677573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061069b91906126d7565b6001600160a01b031614806107365750609754604051633581777360e01b815233916001600160a01b0316906335817773906106db908590600401612a84565b60206040518083038186803b1580156106f357600080fd5b505afa158015610707573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061072b91906126d7565b6001600160a01b0316145b806107445750610744611b1c565b6107695760405162461bcd60e51b8152600401610760906132b3565b60405180910390fd5b6001600160a01b0383166000908152609c602052604090205484146107a05760405162461bcd60e51b815260040161076090613261565b6001600160a01b0383166000908152609c602052604081208190555b6000858152609d6020526040902054811015610942576000858152609d6020526040902080546001600160a01b0386169190839081106107f857fe5b6000918252602090912001546001600160a01b0316141561093a576000858152609d60205260409020546001820110156108b9576000858152609d60205260409020805461084d90600163ffffffff611b2816565b8154811061085757fe5b6000918252602080832090910154878352609d909152604090912080546001600160a01b03909216918390811061088a57fe5b9060005260206000200160006101000a8154816001600160a01b0302191690836001600160a01b031602179055505b6000858152609d6020526040902080546108da90600163ffffffff611b2816565b815481106108e457fe5b6000918252602080832090910180546001600160a01b0319169055868252609d90526040902080548061091357fe5b600082815260209020810160001990810180546001600160a01b0319169055019055610942565b6001016107bc565b5050505050565b6001600160a01b03811661096f5760405162461bcd60e51b815260040161076090612f05565b6001600160a01b0381166000908152609b6020526040902054156109a55760405162461bcd60e51b815260040161076090612e55565b60006109b0336105ac565b600090815260986020526040902060020180546001600160a01b0319166001600160a01b03939093169290921790915550565b60009081526065602052604090206002015490565b6000610a03336105ac565b9050610a0e8161137e565b610a2a5760405162461bcd60e51b815260040161076090612b39565b6000908152609860205260409020600701805460ff19169055565b600082815260656020526040902060020154610a639061043b611b6a565b610a7f5760405162461bcd60e51b815260040161076090612bc0565b610a898282611b6e565b5050565b6000610a983361058b565b15610ab55760405162461bcd60e51b815260040161076090612c7d565b6103e8831115610ad75760405162461bcd60e51b8152600401610760906130db565b50609e805460010190819055604080516101206020601f8a018190040282018101909252610100810188815290918291908a908a908190850183828082843760009201829052509385525050336020808501919091526040808501939093528251601f8a01829004820281018201909352888352606090930192899150889081908401838280828437600092018290525093855250505060208083018790524260408085019190915260608401879052600160809094019390935284825260988152919020825180519192610bb192849290910190612515565b506020828101516001830180546001600160a01b039283166001600160a01b031991821617909155604085015160028501805491909316911617905560608301518051610c049260038501920190612515565b506080820151600482015560a0820151600582015560c0820151600682015560e0909101516007909101805460ff1916911515919091179055610c478133611bdd565b7f4013ba65fee075e87ceec32f5b3568314dfcbe8b3aaeb445c76e77823b790c6f81604051610c769190612989565b60405180910390a19695505050505050565b60986020908152600091825260409182902080548351601f60026000196101006001861615020190931692909204918201849004840281018401909452808452909291839190830182828015610d1f5780601f10610cf457610100808354040283529160200191610d1f565b820191906000526020600020905b815481529060010190602001808311610d0257829003601f168201915b505050600180850154600280870154600388018054604080516020601f60001999851615610100029990990190931695909504968701829004820285018201905285845297986001600160a01b0394851698929094169650929450909290830182828015610dce5780601f10610da357610100808354040283529160200191610dce565b820191906000526020600020905b815481529060010190602001808311610db157829003601f168201915b505050506004830154600584015460068501546007909501549394919390925060ff1688565b610dfc611b6a565b6001600160a01b0316816001600160a01b031614610e2c5760405162461bcd60e51b8152600401610760906133a8565b610a898282611c8b565b6000610e41336105ac565b604051630601a91b60e21b81529091503090631806a46c90610e699084908690600401612a4f565b600060405180830381600087803b158015610e8357600080fd5b505af1158015610e97573d6000803e3d6000fd5b505050507fafa229b1d91fef1b7e952744b5504745de9616d7ef081a95b6abbf091a00e5f18183604051610ecc929190612a4f565b60405180910390a15050565b610ee182611ace565b610efd5760405162461bcd60e51b815260040161076090612cfe565b610f068261137e565b610f225760405162461bcd60e51b815260040161076090612d5b565b600082815260986020526040902060060154811015610a895760405162461bcd60e51b8152600401610760906131bf565b80610f5d816110e4565b610f795760405162461bcd60e51b81526004016107609061321c565b610f8233611cfa565b610f9e5760405162461bcd60e51b81526004016107609061318f565b60008281526099602052604090205460ff16610fcc5760405162461bcd60e51b815260040161076090612cc7565b6000828152609960209081526040808320805460ff19169055609a80548251818502810185019093528083526110369383018282801561102b57602002820191906000526020600020905b815481526020019060010190808311611017575b505050505084611e75565b609a5490915081101561108757609a805461105890600163ffffffff611b2816565b8154811061106257fe5b9060005260206000200154609a828154811061107a57fe5b6000918252602090912001555b609a80548061109257fe5b600190038181906000526020600020016000905590557fcf19fe3d2bddcf835796e65da48a848f1f55068c591e1739ce2f9a2037d86e17836040516110d79190612989565b60405180910390a1505050565b6000609e5482111580156110f757508115155b92915050565b6111068161058b565b6111225760405162461bcd60e51b815260040161076090612db0565b50565b6000611130336105ac565b600081815260986020526040902090915061114f906003018484612593565b50505050565b8061115f816110e4565b61117b5760405162461bcd60e51b81526004016107609061321c565b61118433611cfa565b6111a05760405162461bcd60e51b81526004016107609061318f565b60008281526099602052604090205460ff16156111cf5760405162461bcd60e51b815260040161076090612ece565b600082815260996020526040808220805460ff19166001908117909155609a805491820181559092527f44da158ba27f9252712a74ff6a55c5d531f69609f1f6e7f17c4443a8e2089be4909101839055517f35f72fa856b7982df44607525004d95014aa9153928eab40bb222857d021a21190610ecc908490612989565b6000611258336105ac565b9050836001600160a01b03166112d984848080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250506040516112cd92506112b291508690602001612989565b60405160208183030381529060405280519060200120611eb5565b9063ffffffff611ee516565b6001600160a01b0316146112ff5760405162461bcd60e51b8152600401610760906132ea565b6001600160a01b0384166000908152609b6020526040902054156113355760405162461bcd60e51b815260040161076090613158565b61133f8185612013565b7fa14268bedb4efdc41530188f4a7cbeb2df7644eba551d50504ca31c86fff79318185604051611370929190612a4f565b60405180910390a150505050565b60008161138a816110e4565b6113a65760405162461bcd60e51b81526004016107609061321c565b505060009081526098602052604090206007015460ff1690565b60006113cb336105ac565b600081815260986020526040902090915061114f908484612593565b6000828152606560205260408120611405908363ffffffff6120b816565b9392505050565b6000828152606560205260408120611405908363ffffffff6120c416565b600081565b600061143a336105ac565b60009081526098602052604090206006019190915550565b6097546001600160a01b031681565b611469612601565b81611473816110e4565b61148f5760405162461bcd60e51b81526004016107609061321c565b600083815260986020908152604091829020825181546002610100600183161581026000190190921604601f81018590049094028201610120908101909552810183815290939192849284919084018282801561152d5780601f106115025761010080835404028352916020019161152d565b820191906000526020600020905b81548152906001019060200180831161151057829003601f168201915b50505091835250506001828101546001600160a01b0390811660208085019190915260028086015490921660408086019190915260038601805482516101009682161596909602600019011693909304601f8101839004830285018301909152808452606090940193908301828280156115e85780601f106115bd576101008083540402835291602001916115e8565b820191906000526020600020905b8154815290600101906020018083116115cb57829003601f168201915b505050918352505060048201546020820152600582015460408201526006820154606082015260079091015460ff1615156080909101529392505050565b6001600160a01b0381166000908152609c6020526040902054806105a75760405162461bcd60e51b815260040161076090613319565b600081611668846105ac565b14611674576000611405565b50600192915050565b6060609a8054806020026020016040519081016040528092919081815260200182805480156116cb57602002820191906000526020600020905b8154815260200190600101908083116116b7575b505050505090505b90565b600054610100900460ff16806116ef57506116ef6120d9565b806116fd575060005460ff16155b6117195760405162461bcd60e51b81526004016107609061304b565b600054610100900460ff16158015611744576000805460ff1961ff0019909116610100171660011790555b61174d826120df565b609f805460ff191660011790558015610a89576000805461ff00191690555050565b60008181526065602052604081206110f79061217e565b609754604051633581777360e01b815260009182916001600160a01b03909116906335817773906117b99060040161312a565b60206040518083038186803b1580156117d157600080fd5b505afa1580156117e5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061180991906126d7565b9050806001600160a01b031663ff1f779961182385611461565b60200151856040518363ffffffff1660e01b81526004016118459291906129a6565b602060405180830381600087803b15801561185f57600080fd5b505af1158015611873573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061140591906128b4565b6000818152609d60209081526040918290208054835181840281018401909452808452606093928301828280156118f757602002820191906000526020600020905b81546001600160a01b031681526001909101906020018083116118d9575b50505050509050919050565b600061190e336105ac565b90506119198161137e565b156119365760405162461bcd60e51b815260040161076090613364565b6000908152609860205260409020600701805460ff19166001179055565b6000828152606560205260409020600201546119729061043b611b6a565b610e2c5760405162461bcd60e51b815260040161076090612f3c565b609a818154811061199b57fe5b600091825260209091200154905081565b609e5481565b6119ba611b1c565b6119d65760405162461bcd60e51b815260040161076090612c0f565b609f805460ff19169055565b806119ec816110e4565b611a085760405162461bcd60e51b81526004016107609061321c565b33611a1283611461565b604001516001600160a01b031614611a3c5760405162461bcd60e51b815260040161076090612de5565b600082815260986020526040902060020180546001600160a01b0319169055611a658233611bdd565b600082815260986020526040908190206001015490517f9fe443dfd97eb75800b1e19c356677bca2625789663d07eed1c2c0dbe5488f3c91610ecc9185916001600160a01b031690612a4f565b609f5460ff1681565b6060611ac9610505336105ac565b905090565b600081611ada816110e4565b611af65760405162461bcd60e51b81526004016107609061321c565b60008381526099602052604090205460ff1680611405575050609f5460ff161592915050565b6000611ac9813361140c565b600061140583836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612189565b3390565b6000828152606560205260409020611b8c908263ffffffff6121b516565b15610a8957611b99611b6a565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6001600160a01b0381166000908152609b6020526040902054821415611c0257610a89565b6001600160a01b0381166000908152609b602052604090205415611c385760405162461bcd60e51b815260040161076090612f8c565b600082815260986020908152604080832060010180546001600160a01b039081168552609b8085528386208690559516808552609c845282852087905581546001600160a01b0319161790559290522055565b6000828152606560205260409020611ca9908263ffffffff6121ca16565b15610a8957611cb6611b6a565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b60975460405160009182916001600160a01b039091169063ec56a37390611d2390602001612971565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611d559190612989565b60206040518083038186803b158015611d6d57600080fd5b505afa158015611d81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da591906126d7565b90506001600160a01b03811615611e65576000819050806001600160a01b03166391d14854604051611dd69061295b565b6040519081900381206001600160e01b031960e084901b168252611dfe918890600401612a4f565b60206040518083038186803b158015611e1657600080fd5b505afa158015611e2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e4e9190612771565b80611e5c5750611e5c611b1c565b925050506105a7565b611e6d611b1c565b9150506105a7565b6000805b8351811015611eac5782848281518110611e8f57fe5b60200260200101511415611ea45790506110f7565b600101611e79565b50509051919050565b600081604051602001611ec8919061292a565b604051602081830303815290604052805190602001209050919050565b60008151604114611f085760405162461bcd60e51b815260040161076090612c46565b60208201516040830151606084015160001a7f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0821115611f5a5760405162461bcd60e51b815260040161076090612e8c565b8060ff16601b14158015611f7257508060ff16601c14155b15611f8f5760405162461bcd60e51b815260040161076090612fd2565b600060018783868660405160008152602001604052604051611fb49493929190612a66565b6020604051602081039080840390855afa158015611fd6573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166120095760405162461bcd60e51b815260040161076090612b02565b9695505050505050565b6001600160a01b0381166000908152609c602052604090205482141561203857610a89565b6001600160a01b0381166000908152609c60205260409020541561206e5760405162461bcd60e51b8152600401610760906133f7565b6001600160a01b0381166000818152609c60209081526040808320869055858352609d82528220805460018101825590835291200180546001600160a01b03191690911790555050565b600061140583836121df565b6000611405836001600160a01b038416612224565b303b1590565b600054610100900460ff16806120f857506120f86120d9565b80612106575060005460ff16155b6121225760405162461bcd60e51b81526004016107609061304b565b600054610100900460ff1615801561214d576000805460ff1961ff0019909116610100171660011790555b61215561223c565b612160600033610a7f565b612169826122ce565b8015610a89576000805461ff00191690555050565b60006110f782612344565b600081848411156121ad5760405162461bcd60e51b81526004016107609190612a84565b505050900390565b6000611405836001600160a01b038416612348565b6000611405836001600160a01b038416612392565b815460009082106122025760405162461bcd60e51b815260040161076090612b7e565b82600001828154811061221157fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600054610100900460ff168061225557506122556120d9565b80612263575060005460ff16155b61227f5760405162461bcd60e51b81526004016107609061304b565b600054610100900460ff161580156122aa576000805460ff1961ff0019909116610100171660011790555b6122b2612458565b6122ba612458565b8015611122576000805461ff001916905550565b6001600160a01b0381166122f45760405162461bcd60e51b815260040161076090613099565b612306816001600160a01b03166124d9565b6123225760405162461bcd60e51b815260040161076090613014565b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b60006123548383612224565b61238a575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556110f7565b5060006110f7565b6000818152600183016020526040812054801561244e57835460001980830191908101906000908790839081106123c557fe5b90600052602060002001549050808760000184815481106123e257fe5b60009182526020808320909101929092558281526001898101909252604090209084019055865487908061241257fe5b600190038181906000526020600020016000905590558660010160008781526020019081526020016000206000905560019450505050506110f7565b60009150506110f7565b600054610100900460ff168061247157506124716120d9565b8061247f575060005460ff16155b61249b5760405162461bcd60e51b81526004016107609061304b565b600054610100900460ff161580156122ba576000805460ff1961ff0019909116610100171660011790558015611122576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47081811480159061250d57508115155b949350505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061255657805160ff1916838001178555612583565b82800160010185558215612583579182015b82811115612583578251825591602001919060010190612568565b5061258f92915061265a565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106125d45782800160ff19823516178555612583565b82800160010185558215612583579182015b828111156125835782358255916020019190600101906125e6565b6040518061010001604052806060815260200160006001600160a01b0316815260200160006001600160a01b03168152602001606081526020016000815260200160008152602001600081526020016000151581525090565b6116d391905b8082111561258f5760008155600101612660565b60008083601f840112612685578182fd5b50813567ffffffffffffffff81111561269c578182fd5b6020830191508360208285010111156126b457600080fd5b9250929050565b6000602082840312156126cc578081fd5b8135611405816134d2565b6000602082840312156126e8578081fd5b8151611405816134d2565b600080600060408486031215612707578182fd5b8335612712816134d2565b9250602084013567ffffffffffffffff81111561272d578283fd5b61273986828701612674565b9497909650939450505050565b60008060408385031215612758578182fd5b8235612763816134d2565b946020939093013593505050565b600060208284031215612782578081fd5b81518015158114611405578182fd5b6000602082840312156127a2578081fd5b5035919050565b600080604083850312156127bb578182fd5b8235915060208301356127cd816134d2565b809150509250929050565b600080604083850312156127ea578182fd5b50508035926020909101359150565b6000806020838503121561280b578182fd5b823567ffffffffffffffff811115612821578283fd5b61282d85828601612674565b90969095509350505050565b60008060008060008060808789031215612851578182fd5b863567ffffffffffffffff80821115612868578384fd5b6128748a838b01612674565b9098509650602089013591508082111561288c578384fd5b5061289989828a01612674565b979a9699509760408101359660609091013595509350505050565b6000602082840312156128c5578081fd5b5051919050565b6001600160a01b03169052565b15159052565b60008151808452815b81811015612904576020818501810151868301820152016128e8565b818111156129155782602083870101525b50601f01601f19169290920160200192915050565b7f19457468657265756d205369676e6564204d6573736167653a0a3332000000008152601c810191909152603c0190565b6941444d494e5f524f4c4560b01b8152600a0190565b6b29b5b0b632a6b0b730b3b2b960a11b8152600c0190565b90815260200190565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b6020808252825182820181905260009190848201906040850190845b81811015612a005783516001600160a01b0316835292840192918401916001016129db565b50909695505050505050565b6020808252825182820181905260009190848201906040850190845b81811015612a0057835183529284019291840191600101612a28565b901515815260200190565b9182526001600160a01b0316602082015260400190565b93845260ff9290921660208401526040830152606082015260800190565b60006020825261140560208301846128df565b6000610100808352612aab8184018c6128df565b6001600160a01b038b811660208601528a8116604086015284820360608601529150612ad7818a6128df565b925050508560808301528460a08301528360c083015282151560e08301529998505050505050505050565b60208082526018908201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604082015260600190565b60208082526025908201527f416363657074696e67207265717565737420697320616c72656164792064697360408201526418589b195960da1b606082015260800190565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b60208082526017908201527f43616c6c6572206973206e6f7420746865206f776e6572000000000000000000604082015260600190565b6020808252601f908201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604082015260600190565b6020808252602a908201527f56616c696461746f7220776974682073756368206164647265737320616c72656040820152696164792065786973747360b01b606082015260800190565b6020808252601d908201527f56616c696461746f7220697320616c72656164792064697361626c6564000000604082015260600190565b60208082526038908201527f56616c696461746f72206973206e6f7420617574686f72697a656420746f206160408201527f63636570742064656c65676174696f6e20726571756573740000000000000000606082015260800190565b60208082526035908201527f5468652076616c696461746f72206973206e6f742063757272656e746c7920616040820152746363657074696e67206e657720726571756573747360581b606082015260800190565b6020808252818101527f56616c696461746f72206164647265737320646f6573206e6f74206578697374604082015260600190565b6020808252604a908201527f5468652076616c696461746f7220616464726573732063616e6e6f742062652060408201527f6368616e6765642062656361757365206974206973206e6f74207468652061636060820152693a3ab0b61037bbb732b960b11b608082015260a00190565b6020808252601a908201527f4164647265737320616c72656164792072656769737465726564000000000000604082015260600190565b60208082526022908201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604082015261756560f01b606082015260800190565b6020808252601c908201527f56616c696461746f7220697320616c726561647920656e61626c656400000000604082015260600190565b6020808252601a908201527f4e657720616464726573732063616e6e6f74206265206e756c6c000000000000604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526026908201527f4164647265737320697320696e2075736520627920616e6f746865722076616c60408201526534b230ba37b960d11b606082015260800190565b60208082526022908201527f45434453413a20696e76616c6964207369676e6174757265202776272076616c604082015261756560f01b606082015260800190565b60208082526017908201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b60208082526022908201527f436f6e74726163744d616e616765722061646472657373206973206e6f742073604082015261195d60f21b606082015260800190565b6020808252602f908201527f4665652072617465206f662076616c696461746f722073686f756c642062652060408201526e6c6f776572207468616e203130302560881b606082015260800190565b6020808252601490820152732232b632b3b0ba34b7b721b7b73a3937b63632b960611b604082015260600190565b6020808252601b908201527f4e6f6465206164647265737320697320612076616c696461746f720000000000604082015260600190565b60208082526016908201527521b0b63632b91034b9903737ba1030b71030b236b4b760511b604082015260600190565b6020808252603e908201527f416d6f756e7420646f6573206e6f74206d656574207468652076616c6964617460408201527f6f722773206d696e696d756d2064656c65676174696f6e20616d6f756e740000606082015260800190565b60208082526025908201527f56616c696461746f722077697468207375636820494420646f6573206e6f7420604082015264195e1a5cdd60da1b606082015260800190565b60208082526032908201527f56616c696461746f7220646f6573206e6f742068617665207065726d697373696040820152716f6e7320746f20756e6c696e6b206e6f646560701b606082015260800190565b60208082526019908201527f4d6573736167652073656e64657220697320696e76616c696400000000000000604082015260600190565b6020808252601590820152745369676e6174757265206973206e6f74207061737360581b604082015260600190565b6020808252602b908201527f4e6f64652061646472657373206973206e6f742061737369676e656420746f2060408201526a30903b30b634b230ba37b960a91b606082015260800190565b60208082526024908201527f416363657074696e67207265717565737420697320616c726561647920656e61604082015263189b195960e21b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b60208082526026908201527f56616c696461746f722063616e6e6f74206f76657272696465206e6f6465206160408201526564647265737360d01b606082015260800190565b600060208252825161010080602085015261345c6101208501836128df565b6020860151925061347060408601846128cc565b6040860151925061348460608601846128cc565b6060860151858203601f1901608087015292506134a181846128df565b608087015160a087015260a087015160c087015260c087015160e087015260e08701519350612009838701856128d9565b6001600160a01b038116811461112257600080fdfea26469706673582212202a9fb7976f4e5e381c8136cb3bcc0ab7093dc5e53c6a0b0ebadeeb1497c855f764736f6c634300060a0033
[ 0, 4, 7, 9, 6, 10 ]
0x5facd245d1597876d381e275dae31fe605820605
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; struct ProtocolBalance { ProtocolMetadata metadata; AdapterBalance[] adapterBalances; } struct ProtocolMetadata { string name; string description; string websiteURL; string iconURL; uint256 version; } struct AdapterBalance { AdapterMetadata metadata; FullTokenBalance[] balances; } struct AdapterMetadata { address adapterAddress; string adapterType; // "Asset", "Debt" } struct FullTokenBalance { TokenBalance base; TokenBalance[] underlying; } struct TokenBalance { TokenMetadata metadata; uint256 amount; } struct TokenMetadata { address token; string name; string symbol; uint8 decimals; } struct Component { address token; string tokenType; // "ERC20" by default uint256 rate; // price per full share (1e18) } interface ERC20 { function approve(address, uint256) external returns (bool); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); 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) external view returns (uint256); } interface TokenAdapter { /** * @dev MUST return TokenMetadata struct with ERC20-style token info. * struct TokenMetadata { * address token; * string name; * string symbol; * uint8 decimals; * } */ function getMetadata(address token) external view returns (TokenMetadata memory); /** * @dev MUST return array of Component structs with underlying tokens rates for the given token. * struct Component { * address token; // Address of token contract * string tokenType; // Token type ("ERC20" by default) * uint256 rate; // Price per share (1e18) * } */ function getComponents(address token) external view returns (Component[] memory); } interface DODOLpToken { function _OWNER_() external view returns (address); function originToken() external view returns (address); } interface DODO { function _BASE_TOKEN_() external view returns (address); function _BASE_CAPITAL_TOKEN_() external view returns (address); function _QUOTE_TOKEN_() external view returns (address); function getExpectedTarget() external view returns (uint256, uint256); } contract DodoTokenAdapter is TokenAdapter { /** * @return TokenMetadata struct with ERC20-style token info. * @dev Implementation of TokenAdapter interface function. */ function getMetadata(address token) external view override returns (TokenMetadata memory) { return TokenMetadata({ token: token, name: getPoolName(token), symbol: "DLP", decimals: ERC20(token).decimals() }); } /** * @return Array of Component structs with underlying tokens rates for the given token. * @dev Implementation of TokenAdapter interface function. */ function getComponents(address token) external view override returns (Component[] memory) { address dodo = DODOLpToken(token)._OWNER_(); (uint256 baseTarget, uint256 quoteTarget) = DODO(dodo).getExpectedTarget(); address baseToken = DODO(dodo)._BASE_TOKEN_(); address originToken = DODOLpToken(token).originToken(); uint256 underlyingTokenAmount = originToken == baseToken ? baseTarget : quoteTarget; Component[] memory underlyingTokens = new Component[](1); underlyingTokens[0] = Component({ token: originToken, tokenType: "ERC20", rate: underlyingTokenAmount * 1e18 / ERC20(token).totalSupply() }); return underlyingTokens; } function getPoolName(address token) internal view returns (string memory) { address dodo = DODOLpToken(token)._OWNER_(); return string( abi.encodePacked( getSymbol(DODO(dodo)._BASE_TOKEN_()), "/", getSymbol(DODO(dodo)._QUOTE_TOKEN_()), " Pool: ", getSymbol(DODOLpToken(token).originToken()) ) ); } function getSymbol(address token) internal view returns (string memory) { (, bytes memory returnData) = token.staticcall( abi.encodeWithSelector(ERC20(token).symbol.selector) ); if (returnData.length == 32) { return convertToString(abi.decode(returnData, (bytes32))); } else { return abi.decode(returnData, (string)); } } /** * @dev Internal function to convert bytes32 to string and trim zeroes. */ function convertToString(bytes32 data) internal pure returns (string memory) { uint256 counter = 0; bytes memory result; for (uint256 i = 0; i < 32; i++) { if (data[i] != bytes1(0)) { counter++; } } result = new bytes(counter); counter = 0; for (uint256 i = 0; i < 32; i++) { if (data[i] != bytes1(0)) { result[counter] = data[i]; counter++; } } return string(result); } }
0x608060405234801561001057600080fd5b50600436106100365760003560e01c80632a50c1461461003b57806379b1833414610064575b600080fd5b61004e6100493660046109ab565b610084565b60405161005b9190610cb2565b60405180910390f35b6100776100723660046109ab565b610187565b60405161005b9190610c00565b61008c610933565b60405180608001604052808373ffffffffffffffffffffffffffffffffffffffff1681526020016100bc84610522565b81526020016040518060400160405280600381526020017f444c50000000000000000000000000000000000000000000000000000000000081525081526020018373ffffffffffffffffffffffffffffffffffffffff1663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561014257600080fd5b505afa158015610156573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061017a9190610ade565b60ff16905290505b919050565b606060008273ffffffffffffffffffffffffffffffffffffffff166316048bc46040518163ffffffff1660e01b815260040160206040518083038186803b1580156101d157600080fd5b505afa1580156101e5573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061020991906109ce565b90506000808273ffffffffffffffffffffffffffffffffffffffff1663ffa642256040518163ffffffff1660e01b8152600401604080518083038186803b15801561025357600080fd5b505afa158015610267573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061028b9190610abb565b9150915060008373ffffffffffffffffffffffffffffffffffffffff16634a248d2a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156102d757600080fd5b505afa1580156102eb573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061030f91906109ce565b905060008673ffffffffffffffffffffffffffffffffffffffff166313096a416040518163ffffffff1660e01b815260040160206040518083038186803b15801561035957600080fd5b505afa15801561036d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061039191906109ce565b905060008273ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16146103ce57836103d0565b845b60408051600180825281830190925291925060609190816020015b6103f3610974565b8152602001906001900390816103eb57905050905060405180606001604052808473ffffffffffffffffffffffffffffffffffffffff1681526020016040518060400160405280600581526020017f455243323000000000000000000000000000000000000000000000000000000081525081526020018a73ffffffffffffffffffffffffffffffffffffffff166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b1580156104b057600080fd5b505afa1580156104c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906104e891906109ea565b84670de0b6b3a764000002816104fa57fe5b048152508160008151811061050b57fe5b602090810291909101015298975050505050505050565b606060008273ffffffffffffffffffffffffffffffffffffffff166316048bc46040518163ffffffff1660e01b815260040160206040518083038186803b15801561056c57600080fd5b505afa158015610580573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105a491906109ce565b905061062c8173ffffffffffffffffffffffffffffffffffffffff16634a248d2a6040518163ffffffff1660e01b815260040160206040518083038186803b1580156105ef57600080fd5b505afa158015610603573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061062791906109ce565b6106e7565b6106758273ffffffffffffffffffffffffffffffffffffffff1663d4b970466040518163ffffffff1660e01b815260040160206040518083038186803b1580156105ef57600080fd5b6106be8573ffffffffffffffffffffffffffffffffffffffff166313096a416040518163ffffffff1660e01b815260040160206040518083038186803b1580156105ef57600080fd5b6040516020016106d093929190610b65565b604051602081830303815290604052915050919050565b60408051600481526024810182526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f95d89b41000000000000000000000000000000000000000000000000000000001790529051606091829173ffffffffffffffffffffffffffffffffffffffff85169161076591610b49565b600060405180830381855afa9150503d80600081146107a0576040519150601f19603f3d011682016040523d82523d6000602084013e6107a5565b606091505b509150508051602014156107d7576107cf818060200190518101906107ca91906109ea565b6107eb565b915050610182565b808060200190518101906107cf9190610a02565b6060600081815b602081101561084357600085826020811061080957fe5b1a60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19161461083b576001909201915b6001016107f2565b508167ffffffffffffffff8111801561085b57600080fd5b506040519080825280601f01601f191660200182016040528015610886576020820181803683370190505b50600092509050815b602081101561092b5760008582602081106108a657fe5b1a60f81b7effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191614610923578481602081106108dd57fe5b1a60f81b8284815181106108ed57fe5b60200101907effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1916908160001a9053506001909201915b60010161088f565b509392505050565b6040518060800160405280600073ffffffffffffffffffffffffffffffffffffffff1681526020016060815260200160608152602001600060ff1681525090565b6040518060600160405280600073ffffffffffffffffffffffffffffffffffffffff16815260200160608152602001600081525090565b6000602082840312156109bc578081fd5b81356109c781610d72565b9392505050565b6000602082840312156109df578081fd5b81516109c781610d72565b6000602082840312156109fb578081fd5b5051919050565b600060208284031215610a13578081fd5b815167ffffffffffffffff80821115610a2a578283fd5b81840185601f820112610a3b578384fd5b8051925081831115610a4b578384fd5b60405160207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8601168201018181108482111715610a89578586fd5b604052838152818401602001871015610aa0578485fd5b610ab1846020830160208501610d42565b9695505050505050565b60008060408385031215610acd578081fd5b505080516020909101519092909150565b600060208284031215610aef578081fd5b815160ff811681146109c7578182fd5b60008151808452610b17816020860160208601610d42565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b60008251610b5b818460208701610d42565b9190910192915050565b60008451610b77818460208901610d42565b8083017f2f00000000000000000000000000000000000000000000000000000000000000815285519150610bb2826001830160208901610d42565b8181017f20506f6f6c3a2000000000000000000000000000000000000000000000000000600182015285519250610bf0836008830160208901610d42565b9091016008019695505050505050565b60208082528251828201819052600091906040908185019080840286018301878501865b83811015610ca4577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc08984030185528151606073ffffffffffffffffffffffffffffffffffffffff825116855288820151818a870152610c8682870182610aff565b92890151958901959095525094870194925090860190600101610c24565b509098975050505050505050565b60006020825273ffffffffffffffffffffffffffffffffffffffff8351166020830152602083015160806040840152610cee60a0840182610aff565b604085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0848203016060850152610d298183610aff565b60ff606087015116608086015280935050505092915050565b60005b83811015610d5d578181015183820152602001610d45565b83811115610d6c576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff81168114610d9457600080fd5b5056fea264697066735822122086d153810835fae5af16a88dddc7f632d90540b3d7da7277d5b13070353e9c8c64736f6c63430006050033
[ 38 ]
0x5FC48Bc1B54F718d6B307C8027207cD7c3bcc0EF
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ERC20 { function totalSupply() external view returns (uint); function decimals() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); } interface IFeature { enum OwnerSignature { Anyone, // Anyone Required, // Owner required Optional, // Owner and/or guardians Disallowed // guardians only } /** * @notice Utility method to recover any ERC20 token that was sent to the Feature by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; /** * @notice Inits a Feature for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(address _wallet) external; /** * @notice Helper method to check if an address is an authorised feature of a target wallet. * @param _wallet The target wallet. * @param _feature The address. */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) external view returns (bool); /** * @notice Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures and the wallet owner signature requirement. */ function getRequiredSignatures(address _wallet, bytes calldata _data) external view returns (uint256, OwnerSignature); /** * @notice Gets the list of static call signatures that this feature responds to on behalf of wallets */ function getStaticCallSignatures() external view returns (bytes4[] memory); } interface IGuardianStorage { /** * @notice Lets an authorised module add a guardian to a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(address _wallet, address _guardian) external; /** * @notice Lets an authorised module revoke a guardian from a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(address _wallet, address _guardian) external; /** * @notice Checks if an account is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The account. * @return true if the account is a guardian for a wallet. */ function isGuardian(address _wallet, address _guardian) external view returns (bool); function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, uint256 _releaseAfter) external; function getGuardians(address _wallet) external view returns (address[] memory); function guardianCount(address _wallet) external view returns (uint256); } interface ILimitStorage { struct Limit { // the current limit uint128 current; // the pending limit if any uint128 pending; // when the pending limit becomes the current limit uint64 changeAfter; } struct DailySpent { // The amount already spent during the current period uint128 alreadySpent; // The end of the current period uint64 periodEnd; } function setLimit(address _wallet, Limit memory _limit) external; function getLimit(address _wallet) external view returns (Limit memory _limit); function setDailySpent(address _wallet, DailySpent memory _dailySpent) external; function getDailySpent(address _wallet) external view returns (DailySpent memory _dailySpent); function setLimitAndDailySpent(address _wallet, Limit memory _limit, DailySpent memory _dailySpent) external; function getLimitAndDailySpent(address _wallet) external view returns (Limit memory _limit, DailySpent memory _dailySpent); } interface ILockStorage { function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, address _locker, uint256 _releaseAfter) external; } interface IModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } interface IVersionManager { /** * @notice Returns true if the feature is authorised for the wallet * @param _wallet The target wallet. * @param _feature The feature. */ function isFeatureAuthorised(address _wallet, address _feature) external view returns (bool); /** * @notice Lets a feature (caller) invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function checkAuthorisedFeatureAndInvokeWallet( address _wallet, address _to, uint256 _value, bytes calldata _data ) external returns (bytes memory _res); /* ******* Backward Compatibility with old Storages and BaseWallet *************** */ /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _wallet, address _newOwner) external; /** * @notice Lets a feature write data to a storage contract. * @param _wallet The target wallet. * @param _storage The storage contract. * @param _data The data of the call */ function invokeStorage(address _wallet, address _storage, bytes calldata _data) external; /** * @notice Upgrade a wallet to a new version. * @param _wallet the wallet to upgrade * @param _toVersion the new version */ function upgradeWallet(address _wallet, uint256 _toVersion) external; } interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library Utils { /** * @notice Helper method to recover the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); address recoveredAddress = ecrecover(_signedHash, v, r, s); require(recoveredAddress != address(0), "Utils: ecrecover returned 0"); return recoveredAddress; } /** * @notice Helper method to parse data and extract the method signature. */ function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solhint-disable-next-line no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } /** * @notice Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; if (a % b == 0) { return c; } else { return c + 1; } } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } return b; } } contract BaseFeature is IFeature { // Empty calldata bytes constant internal EMPTY_BYTES = ""; // Mock token address for ETH address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // The address of the Lock storage ILockStorage internal lockStorage; // The address of the Version Manager IVersionManager internal versionManager; event FeatureCreated(bytes32 name); /** * @notice Throws if the wallet is locked. */ modifier onlyWhenUnlocked(address _wallet) { require(!lockStorage.isLocked(_wallet), "BF: wallet locked"); _; } /** * @notice Throws if the sender is not the VersionManager. */ modifier onlyVersionManager() { require(msg.sender == address(versionManager), "BF: caller must be VersionManager"); _; } /** * @notice Throws if the sender is not the owner of the target wallet. */ modifier onlyWalletOwner(address _wallet) { require(isOwner(_wallet, msg.sender), "BF: must be wallet owner"); _; } /** * @notice Throws if the sender is not an authorised feature of the target wallet. */ modifier onlyWalletFeature(address _wallet) { require(versionManager.isFeatureAuthorised(_wallet, msg.sender), "BF: must be a wallet feature"); _; } /** * @notice Throws if the sender is not the owner of the target wallet or the feature itself. */ modifier onlyWalletOwnerOrFeature(address _wallet) { // Wrapping in an internal method reduces deployment cost by avoiding duplication of inlined code verifyOwnerOrAuthorisedFeature(_wallet, msg.sender); _; } constructor( ILockStorage _lockStorage, IVersionManager _versionManager, bytes32 _name ) public { lockStorage = _lockStorage; versionManager = _versionManager; emit FeatureCreated(_name); } /** * @inheritdoc IFeature */ function recoverToken(address _token) external virtual override { uint total = ERC20(_token).balanceOf(address(this)); _token.call(abi.encodeWithSelector(ERC20(_token).transfer.selector, address(versionManager), total)); } /** * @notice Inits the feature for a wallet by doing nothing. * @dev !! Overriding methods need make sure `init()` can only be called by the VersionManager !! * @param _wallet The wallet. */ function init(address _wallet) external virtual override {} /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external virtual view override returns (uint256, OwnerSignature) { revert("BF: disabled method"); } /** * @inheritdoc IFeature */ function getStaticCallSignatures() external virtual override view returns (bytes4[] memory _sigs) {} /** * @inheritdoc IFeature */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) public override view returns (bool) { return versionManager.isFeatureAuthorised(_wallet, _feature); } /** * @notice Checks that the wallet address provided as the first parameter of _data matches _wallet * @return false if the addresses are different. */ function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet = abi.decode(_data[4:], (address)); return dataWallet == _wallet; } /** * @notice Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(address _wallet, address _addr) internal view returns (bool) { return IWallet(_wallet).owner() == _addr; } /** * @notice Verify that the caller is an authorised feature or the wallet owner. * @param _wallet The target wallet. * @param _sender The caller. */ function verifyOwnerOrAuthorisedFeature(address _wallet, address _sender) internal view { require(isFeatureAuthorisedInVersionManager(_wallet, _sender) || isOwner(_wallet, _sender), "BF: must be owner or feature"); } /** * @notice Helper method to invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) { _res = versionManager.checkAuthorisedFeatureAndInvokeWallet(_wallet, _to, _value, _data); } } contract RecoveryManager is BaseFeature { bytes32 constant NAME = "RecoveryManager"; bytes4 constant internal EXECUTE_RECOVERY_PREFIX = bytes4(keccak256("executeRecovery(address,address)")); bytes4 constant internal FINALIZE_RECOVERY_PREFIX = bytes4(keccak256("finalizeRecovery(address)")); bytes4 constant internal CANCEL_RECOVERY_PREFIX = bytes4(keccak256("cancelRecovery(address)")); bytes4 constant internal TRANSFER_OWNERSHIP_PREFIX = bytes4(keccak256("transferOwnership(address,address)")); struct RecoveryConfig { address recovery; uint64 executeAfter; uint32 guardianCount; } // Wallet specific storage mapping (address => RecoveryConfig) internal recoveryConfigs; // Recovery period uint256 public recoveryPeriod; // Lock period uint256 public lockPeriod; // Guardian Storage IGuardianStorage public guardianStorage; // *************** Events *************************** // event RecoveryExecuted(address indexed wallet, address indexed _recovery, uint64 executeAfter); event RecoveryFinalized(address indexed wallet, address indexed _recovery); event RecoveryCanceled(address indexed wallet, address indexed _recovery); event OwnershipTransfered(address indexed wallet, address indexed _newOwner); // *************** Modifiers ************************ // /** * @notice Throws if there is no ongoing recovery procedure. */ modifier onlyWhenRecovery(address _wallet) { require(recoveryConfigs[_wallet].executeAfter > 0, "RM: there must be an ongoing recovery"); _; } /** * @notice Throws if there is an ongoing recovery procedure. */ modifier notWhenRecovery(address _wallet) { require(recoveryConfigs[_wallet].executeAfter == 0, "RM: there cannot be an ongoing recovery"); _; } // *************** Constructor ************************ // constructor( ILockStorage _lockStorage, IGuardianStorage _guardianStorage, IVersionManager _versionManager, uint256 _recoveryPeriod, uint256 _lockPeriod ) BaseFeature(_lockStorage, _versionManager, NAME) public { // For the wallet to be secure we must have recoveryPeriod >= securityPeriod + securityWindow // where securityPeriod and securityWindow are the security parameters of adding/removing guardians // and confirming large transfers. require(_lockPeriod >= _recoveryPeriod, "RM: insecure security periods"); recoveryPeriod = _recoveryPeriod; lockPeriod = _lockPeriod; guardianStorage = _guardianStorage; } // *************** External functions ************************ // /** * @notice Lets the guardians start the execution of the recovery procedure. * Once triggered the recovery is pending for the security period before it can be finalised. * Must be confirmed by N guardians, where N = ((Nb Guardian + 1) / 2). * @param _wallet The target wallet. * @param _recovery The address to which ownership should be transferred. */ function executeRecovery(address _wallet, address _recovery) external onlyWalletFeature(_wallet) notWhenRecovery(_wallet) { validateNewOwner(_wallet, _recovery); RecoveryConfig storage config = recoveryConfigs[_wallet]; config.recovery = _recovery; config.executeAfter = uint64(block.timestamp + recoveryPeriod); config.guardianCount = uint32(guardianStorage.guardianCount(_wallet)); setLock(_wallet, block.timestamp + lockPeriod); emit RecoveryExecuted(_wallet, _recovery, config.executeAfter); } /** * @notice Finalizes an ongoing recovery procedure if the security period is over. * The method is public and callable by anyone to enable orchestration. * @param _wallet The target wallet. */ function finalizeRecovery(address _wallet) external onlyWhenRecovery(_wallet) { RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; require(uint64(block.timestamp) > config.executeAfter, "RM: the recovery period is not over yet"); address recoveryOwner = config.recovery; delete recoveryConfigs[_wallet]; versionManager.setOwner(_wallet, recoveryOwner); setLock(_wallet, 0); emit RecoveryFinalized(_wallet, recoveryOwner); } /** * @notice Lets the owner cancel an ongoing recovery procedure. * Must be confirmed by N guardians, where N = ((Nb Guardian + 1) / 2) - 1. * @param _wallet The target wallet. */ function cancelRecovery(address _wallet) external onlyWalletFeature(_wallet) onlyWhenRecovery(_wallet) { RecoveryConfig storage config = recoveryConfigs[address(_wallet)]; address recoveryOwner = config.recovery; delete recoveryConfigs[_wallet]; setLock(_wallet, 0); emit RecoveryCanceled(_wallet, recoveryOwner); } /** * @notice Lets the owner transfer the wallet ownership. This is executed immediately. * @param _wallet The target wallet. * @param _newOwner The address to which ownership should be transferred. */ function transferOwnership(address _wallet, address _newOwner) external onlyWalletFeature(_wallet) onlyWhenUnlocked(_wallet) { validateNewOwner(_wallet, _newOwner); versionManager.setOwner(_wallet, _newOwner); emit OwnershipTransfered(_wallet, _newOwner); } /** * @notice Gets the details of the ongoing recovery procedure if any. * @param _wallet The target wallet. */ function getRecovery(address _wallet) external view returns(address _address, uint64 _executeAfter, uint32 _guardianCount) { RecoveryConfig storage config = recoveryConfigs[_wallet]; return (config.recovery, config.executeAfter, config.guardianCount); } /** * @inheritdoc IFeature */ function getRequiredSignatures(address _wallet, bytes calldata _data) external view override returns (uint256, OwnerSignature) { bytes4 methodId = Utils.functionPrefix(_data); if (methodId == EXECUTE_RECOVERY_PREFIX) { uint walletGuardians = guardianStorage.guardianCount(_wallet); require(walletGuardians > 0, "RM: no guardians set on wallet"); uint numberOfSignaturesRequired = Utils.ceil(walletGuardians, 2); return (numberOfSignaturesRequired, OwnerSignature.Disallowed); } if (methodId == FINALIZE_RECOVERY_PREFIX) { return (0, OwnerSignature.Anyone); } if (methodId == CANCEL_RECOVERY_PREFIX) { uint numberOfSignaturesRequired = Utils.ceil(recoveryConfigs[_wallet].guardianCount + 1, 2); return (numberOfSignaturesRequired, OwnerSignature.Optional); } if (methodId == TRANSFER_OWNERSHIP_PREFIX) { uint majorityGuardians = Utils.ceil(guardianStorage.guardianCount(_wallet), 2); uint numberOfSignaturesRequired = SafeMath.add(majorityGuardians, 1); return (numberOfSignaturesRequired, OwnerSignature.Required); } revert("RM: unknown method"); } // *************** Internal Functions ********************* // function validateNewOwner(address _wallet, address _newOwner) internal view { require(_newOwner != address(0), "RM: new owner address cannot be null"); require(!guardianStorage.isGuardian(_wallet, _newOwner), "RM: new owner address cannot be a guardian"); } function setLock(address _wallet, uint256 _releaseAfter) internal { versionManager.invokeStorage( _wallet, address(lockStorage), abi.encodeWithSelector(lockStorage.setLock.selector, _wallet, address(this), _releaseAfter) ); } }
0x608060405234801561001057600080fd5b50600436106100df5760003560e01c80639769c3fe1161008c578063b0ba4da011610066578063b0ba4da0146102ef578063c90db4471461031d578063d89784fc14610343578063ea2347e614610367576100df565b80639769c3fe1461022a5780639be65a6014610287578063a287fdbd146102ad576100df565b80633b73d67f116100bd5780633b73d67f1461014c5780633fd8b02f146101f45780636d435421146101fc576100df565b806316c3e22f146100e457806319ab453c146100fe578063315a7af314610126575b600080fd5b6100ec6103bf565b60408051918252519081900360200190f35b6101246004803603602081101561011457600080fd5b50356001600160a01b03166103c5565b005b6101246004803603602081101561013c57600080fd5b50356001600160a01b03166103c8565b6101cc6004803603604081101561016257600080fd5b6001600160a01b03823516919081019060408101602082013564010000000081111561018d57600080fd5b82018360208201111561019f57600080fd5b803590602001918460018302840111640100000000831117156101c157600080fd5b509092509050610570565b604051808381526020018260038111156101e257fe5b81526020019250505060405180910390f35b6100ec6108b6565b6101246004803603604081101561021257600080fd5b506001600160a01b03813581169160200135166108bc565b6102506004803603602081101561024057600080fd5b50356001600160a01b0316610b2c565b604080516001600160a01b03909416845267ffffffffffffffff909216602084015263ffffffff1682820152519081900360600190f35b6101246004803603602081101561029d57600080fd5b50356001600160a01b0316610b6c565b6102db600480360360408110156102c357600080fd5b506001600160a01b0381358116916020013516610ceb565b604080519115158252519081900360200190f35b6101246004803603604081101561030557600080fd5b506001600160a01b0381358116916020013516610d79565b6101246004803603602081101561033357600080fd5b50356001600160a01b031661103e565b61034b6111ec565b604080516001600160a01b039092168252519081900360200190f35b61036f6111fb565b60408051602080825283518183015283519192839290830191858101910280838360005b838110156103ab578181015183820152602001610393565b505050509050019250505060405180910390f35b60035481565b50565b6001600160a01b0381166000908152600260205260409020548190600160a01b900467ffffffffffffffff1661042f5760405162461bcd60e51b81526004018080602001828103825260258152602001806115986025913960400191505060405180910390fd5b6001600160a01b0382166000908152600260205260409020805467ffffffffffffffff600160a01b9091048116429091161161049c5760405162461bcd60e51b81526004018080602001828103825260278152602001806115716027913960400191505060405180910390fd5b80546001600160a01b038481166000818152600260205260408082208290556001548151630a669ef360e21b8152600481019490945294841660248401819052905190949093169263299a7bcc92604480820193929182900301818387803b15801561050757600080fd5b505af115801561051b573d6000803e3d6000fd5b5050505061052a846000611200565b806001600160a01b0316846001600160a01b03167fd8667de85dae2d56d76e700d16de53d21ac2ce4d5549cb0bf51c55fdc37f0bc160405160405180910390a350505050565b60008060006105b485858080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061136192505050565b90506001600160e01b031981167fb0ba4da00000000000000000000000000000000000000000000000000000000014156106d557600554604080516328207dbb60e11b81526001600160a01b03898116600483015291516000939290921691635040fb7691602480820192602092909190829003018186803b15801561063957600080fd5b505afa15801561064d573d6000803e3d6000fd5b505050506040513d602081101561066357600080fd5b50519050806106b9576040805162461bcd60e51b815260206004820152601e60248201527f524d3a206e6f20677561726469616e7320736574206f6e2077616c6c65740000604482015290519081900360640190fd5b60006106c68260026113c2565b9450600393506108ae92505050565b6001600160e01b031981167f315a7af30000000000000000000000000000000000000000000000000000000014156107145760008092509250506108ae565b6001600160e01b031981167fc90db44700000000000000000000000000000000000000000000000000000000141561078d576001600160a01b038616600090815260026020819052604082205461077f91600160e01b90910463ffffffff90811660010116906113c2565b9350600292506108ae915050565b6001600160e01b031981167f6d43542100000000000000000000000000000000000000000000000000000000141561086157600554604080516328207dbb60e11b81526001600160a01b0389811660048301529151600093610843931691635040fb76916024808301926020929190829003018186803b15801561081057600080fd5b505afa158015610824573d6000803e3d6000fd5b505050506040513d602081101561083a57600080fd5b505160026113c2565b905060006108528260016113f0565b9450600193506108ae92505050565b6040805162461bcd60e51b815260206004820152601260248201527f524d3a20756e6b6e6f776e206d6574686f640000000000000000000000000000604482015290519081900360640190fd5b935093915050565b60045481565b60015460408051635a51fd4360e01b81526001600160a01b038086166004830152336024830152915185939290921691635a51fd4391604480820192602092909190829003018186803b15801561091257600080fd5b505afa158015610926573d6000803e3d6000fd5b505050506040513d602081101561093c57600080fd5b505161098f576040805162461bcd60e51b815260206004820152601c60248201527f42463a206d75737420626520612077616c6c6574206665617475726500000000604482015290519081900360640190fd5b600054604080517f4a4fbeec0000000000000000000000000000000000000000000000000000000081526001600160a01b038087166004830152915186939290921691634a4fbeec91602480820192602092909190829003018186803b1580156109f857600080fd5b505afa158015610a0c573d6000803e3d6000fd5b505050506040513d6020811015610a2257600080fd5b505115610a76576040805162461bcd60e51b815260206004820152601160248201527f42463a2077616c6c6574206c6f636b6564000000000000000000000000000000604482015290519081900360640190fd5b610a808484611451565b60015460408051630a669ef360e21b81526001600160a01b03878116600483015286811660248301529151919092169163299a7bcc91604480830192600092919082900301818387803b158015610ad657600080fd5b505af1158015610aea573d6000803e3d6000fd5b50506040516001600160a01b038087169350871691507f0d18b5fd22306e373229b9439188228edca81207d1667f604daf6cef8aa3ee6790600090a350505050565b6001600160a01b0390811660009081526002602052604090205490811691600160a01b820467ffffffffffffffff1691600160e01b900463ffffffff1690565b6000816001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b158015610bbb57600080fd5b505afa158015610bcf573d6000803e3d6000fd5b505050506040513d6020811015610be557600080fd5b5051600154604080516001600160a01b039283166024820152604480820185905282518083039091018152606490910182526020810180516001600160e01b03167fa9059cbb00000000000000000000000000000000000000000000000000000000178152915181519495509286169390929182918083835b60208310610c7d5780518252601f199092019160209182019101610c5e565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114610cdf576040519150601f19603f3d011682016040523d82523d6000602084013e610ce4565b606091505b5050505050565b60015460408051635a51fd4360e01b81526001600160a01b038581166004830152848116602483015291516000939290921691635a51fd4391604480820192602092909190829003018186803b158015610d4457600080fd5b505afa158015610d58573d6000803e3d6000fd5b505050506040513d6020811015610d6e57600080fd5b505190505b92915050565b60015460408051635a51fd4360e01b81526001600160a01b038086166004830152336024830152915185939290921691635a51fd4391604480820192602092909190829003018186803b158015610dcf57600080fd5b505afa158015610de3573d6000803e3d6000fd5b505050506040513d6020811015610df957600080fd5b5051610e4c576040805162461bcd60e51b815260206004820152601c60248201527f42463a206d75737420626520612077616c6c6574206665617475726500000000604482015290519081900360640190fd5b6001600160a01b0383166000908152600260205260409020548390600160a01b900467ffffffffffffffff1615610eb45760405162461bcd60e51b81526004018080602001828103825260278152602001806115e16027913960400191505060405180910390fd5b610ebe8484611451565b6001600160a01b0380851660008181526002602090815260409182902080548886167fffffffffffffffffffffffff00000000000000000000000000000000000000009091161780825560035467ffffffffffffffff4290910116600160a01b027fffffffff0000000000000000ffffffffffffffffffffffffffffffffffffffff90911617815560055483516328207dbb60e11b81526004810195909552925190949290921692635040fb769260248083019392829003018186803b158015610f8757600080fd5b505afa158015610f9b573d6000803e3d6000fd5b505050506040513d6020811015610fb157600080fd5b5051815463ffffffff909116600160e01b026001600160e01b03909116178155600454610fe19086904201611200565b805460408051600160a01b90920467ffffffffffffffff168252516001600160a01b0386811692908816917f5f59bfd9baba55ae30bb440923cbbe30987d50e12a4e9134ffac3fd9afc3526d916020908290030190a35050505050565b60015460408051635a51fd4360e01b81526001600160a01b038085166004830152336024830152915184939290921691635a51fd4391604480820192602092909190829003018186803b15801561109457600080fd5b505afa1580156110a8573d6000803e3d6000fd5b505050506040513d60208110156110be57600080fd5b5051611111576040805162461bcd60e51b815260206004820152601c60248201527f42463a206d75737420626520612077616c6c6574206665617475726500000000604482015290519081900360640190fd5b6001600160a01b0382166000908152600260205260409020548290600160a01b900467ffffffffffffffff166111785760405162461bcd60e51b81526004018080602001828103825260258152602001806115986025913960400191505060405180910390fd5b6001600160a01b0380841660009081526002602052604081208054828255909216906111a5908690611200565b806001600160a01b0316856001600160a01b03167fc45926607303da71dbeffd2ed5c6b00f581982586b697655d19ae4c4d558f25960405160405180910390a35050505050565b6005546001600160a01b031681565b606090565b60015460008054604080516001600160a01b0387811660248084018290523060448086019190915260648086018b9052865180870382018152608496870188526020810180516001600160e01b03167f6b221d140000000000000000000000000000000000000000000000000000000017815297517fe452b7900000000000000000000000000000000000000000000000000000000081526004810195865298861693890184905260609289019283528051918901919091528051949099169863e452b790988c98939791969495929493909301929091908190849084905b838110156112f75781810151838201526020016112df565b50505050905090810190601f1680156113245780820380516001836020036101000a031916815260200191505b50945050505050600060405180830381600087803b15801561134557600080fd5b505af1158015611359573d6000803e3d6000fd5b505050505050565b60006004825110156113ba576040805162461bcd60e51b815260206004820152601a60248201527f524d3a20496e76616c69642066756e6374696f6e507265666978000000000000604482015290519081900360640190fd5b506020015190565b6000808284816113ce57fe5b0490508284816113da57fe5b066113e6579050610d73565b6001019050610d73565b60008282018381101561144a576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6001600160a01b0381166114965760405162461bcd60e51b81526004018080602001828103825260248152602001806115bd6024913960400191505060405180910390fd5b600554604080517fd4ee97340000000000000000000000000000000000000000000000000000000081526001600160a01b03858116600483015284811660248301529151919092169163d4ee9734916044808301926020929190829003018186803b15801561150457600080fd5b505afa158015611518573d6000803e3d6000fd5b505050506040513d602081101561152e57600080fd5b50511561156c5760405162461bcd60e51b815260040180806020018281038252602a815260200180611608602a913960400191505060405180910390fd5b505056fe524d3a20746865207265636f7665727920706572696f64206973206e6f74206f76657220796574524d3a207468657265206d75737420626520616e206f6e676f696e67207265636f76657279524d3a206e6577206f776e657220616464726573732063616e6e6f74206265206e756c6c524d3a2074686572652063616e6e6f7420626520616e206f6e676f696e67207265636f76657279524d3a206e6577206f776e657220616464726573732063616e6e6f74206265206120677561726469616ea264697066735822122083ce219571fba08c472722a2cae64222634ae81ad954852cfebf34e2779c75ae64736f6c634300060c0033
[ 8, 9 ]
0x600184af62a0b4c46b94a5123e11f15399d538da
pragma solidity 0.4.21; contract EIP20Interface { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ /// total amount of tokens uint256 public totalSupply; /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) public view returns (uint256 balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) public returns (bool success); /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); /// @notice `msg.sender` approves `_spender` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of tokens to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) public returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) public view returns (uint256 remaining); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract bulla is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. string public symbol; //An identifier: eg SBX function bulla( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; // Give the creator all initial tokens totalSupply = _initialAmount; // Update total supply name = _tokenName; // Set the name for display purposes decimals = _decimalUnits; // Amount of decimals for display purposes symbol = _tokenSymbol; // Set the symbol for display purposes } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); //solhint-disable-line indent, no-unused-vars return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //solhint-disable-line indent, no-unused-vars return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a723058208e4657f80aa8e069a98de618f22bccfe30dc1286d65ba9a14d74cdf574bcdb300029
[ 38 ]
0x609c9c1432f323ccee720d8bdbe94cf55a618445
pragma solidity 0.6.0; 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 ERC20 is Context { using SafeMath for uint256; mapping (address => uint256) public _balances; mapping (address => mapping (address => uint256)) public _allowances; //need to go public uint256 public _totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) virtual internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } 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{ /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } /** * @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); } } contract Steam is ERC20 { using SafeMath for uint256; modifier onlyUPS() { require(_UPS == _msgSender(), "onlyUPS: Only the UPStkn contract may call this function"); _; } string private _name; address public _UPS; string private _symbol; uint8 private _decimals; uint256 private _maxSupply; uint256 private _steamMinted = 0; event SteamGenerated(address account, uint amount); constructor(uint256 STEAM_maxTokens) public { _name = "STEAM"; _symbol = "STMtkn"; _decimals = 18; _maxSupply = STEAM_maxTokens.mul(1e18); ERC20._mint(_msgSender(), 1e18); _UPS = _msgSender(); } function generateSteam(address account, uint256 amount) external onlyUPS { require((_totalSupply + amount) < _maxSupply, "STEAM token: cannot generate more steam than the max supply"); ERC20._mint(account, amount); _steamMinted = _steamMinted.add(amount); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint256) { return ERC20._totalSupply; } function mySteam(address _address) public view returns(uint256){ return balanceOf(_address); } function getSteamTotalSupply() public view returns(uint256){ return _totalSupply; } function getSteamMaxSupply() public view returns(uint256){ return _maxSupply; } function getSteamMinted() public view returns(uint256){ return _steamMinted; } }
0x608060405234801561001057600080fd5b506004361061012c5760003560e01c80636ebcf607116100ad57806398fd3f581161007157806398fd3f58146105ef578063a457c2d71461063d578063a9059cbb146106a3578063d2bd03b214610709578063dd62ed3e146107275761012c565b80636ebcf607146104545780636f309291146104ac57806370a08231146104f6578063931ad5091461054e57806395d89b411461056c5761012c565b80631ba6b604116100f45780631ba6b6041461030857806323b872dd14610326578063313ce567146103ac57806339509351146103d05780633eaaf86b146104365761012c565b8063024c2ddd146101315780630491d81f146101a957806306fdde0314610201578063095ea7b31461028457806318160ddd146102ea575b600080fd5b6101936004803603604081101561014757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061079f565b6040518082815260200191505060405180910390f35b6101eb600480360360208110156101bf57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506107c4565b6040518082815260200191505060405180910390f35b6102096107d6565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561024957808201518184015260208101905061022e565b50505050905090810190601f1680156102765780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6102d06004803603604081101561029a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610878565b604051808215151515815260200191505060405180910390f35b6102f2610896565b6040518082815260200191505060405180910390f35b6103106108a0565b6040518082815260200191505060405180910390f35b6103926004803603606081101561033c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506108aa565b604051808215151515815260200191505060405180910390f35b6103b4610983565b604051808260ff1660ff16815260200191505060405180910390f35b61041c600480360360408110156103e657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061099a565b604051808215151515815260200191505060405180910390f35b61043e610a4d565b6040518082815260200191505060405180910390f35b6104966004803603602081101561046a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610a53565b6040518082815260200191505060405180910390f35b6104b4610a6b565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6105386004803603602081101561050c57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610a91565b6040518082815260200191505060405180910390f35b610556610ad9565b6040518082815260200191505060405180910390f35b610574610ae3565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156105b4578082015181840152602081019050610599565b50505050905090810190601f1680156105e15780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b61063b6004803603604081101561060557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610b85565b005b6106896004803603604081101561065357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610cb9565b604051808215151515815260200191505060405180910390f35b6106ef600480360360408110156106b957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610d86565b604051808215151515815260200191505060405180910390f35b610711610da4565b6040518082815260200191505060405180910390f35b6107896004803603604081101561073d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610dae565b6040518082815260200191505060405180910390f35b6001602052816000526040600020602052806000526040600020600091509150505481565b60006107cf82610a91565b9050919050565b606060038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561086e5780601f106108435761010080835404028352916020019161086e565b820191906000526020600020905b81548152906001019060200180831161085157829003601f168201915b5050505050905090565b600061088c610885610e35565b8484610e3d565b6001905092915050565b6000600254905090565b6000600254905090565b60006108b7848484611034565b610978846108c3610e35565b6109738560405180606001604052806028815260200161173b60289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000610929610e35565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546112ea9092919063ffffffff16565b610e3d565b600190509392505050565b6000600660009054906101000a900460ff16905090565b6000610a436109a7610e35565b84610a3e85600160006109b8610e35565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546113aa90919063ffffffff16565b610e3d565b6001905092915050565b60025481565b60006020528060005260406000206000915090505481565b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b6000600754905090565b606060058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610b7b5780601f10610b5057610100808354040283529160200191610b7b565b820191906000526020600020905b815481529060010190602001808311610b5e57829003601f168201915b5050505050905090565b610b8d610e35565b73ffffffffffffffffffffffffffffffffffffffff16600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610c32576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260388152602001806117ac6038913960400191505060405180910390fd5b600754816002540110610c90576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252603b8152602001806116b9603b913960400191505060405180910390fd5b610c9a8282611432565b610caf816008546113aa90919063ffffffff16565b6008819055505050565b6000610d7c610cc6610e35565b84610d77856040518060600160405280602581526020016117e46025913960016000610cf0610e35565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546112ea9092919063ffffffff16565b610e3d565b6001905092915050565b6000610d9a610d93610e35565b8484611034565b6001905092915050565b6000600854905090565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610ec3576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806117886024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610f49576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806116976022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1614156110ba576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260258152602001806117636025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415611140576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001806116746023913960400191505060405180910390fd5b6111ab816040518060600160405280602681526020016116f4602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546112ea9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000208190555061123e816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546113aa90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a3505050565b6000838311158290611397576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561135c578082015181840152602081019050611341565b50505050905090810190601f1680156113895780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b600080828401905083811015611428576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614156114d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601f8152602001807f45524332303a206d696e7420746f20746865207a65726f20616464726573730081525060200191505060405180910390fd5b6114ea816002546113aa90919063ffffffff16565b600281905550611541816000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546113aa90919063ffffffff16565b6000808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff16600073ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35050565b600080831415611600576000905061166d565b600082840290508284828161161157fe5b0414611668576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602181526020018061171a6021913960400191505060405180910390fd5b809150505b9291505056fe45524332303a207472616e7366657220746f20746865207a65726f206164647265737345524332303a20617070726f766520746f20746865207a65726f2061646472657373535445414d20746f6b656e3a2063616e6e6f742067656e6572617465206d6f726520737465616d207468616e20746865206d617820737570706c7945524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e6365536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7745524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f20616464726573736f6e6c795550533a204f6e6c792074686520555053746b6e20636f6e7472616374206d61792063616c6c20746869732066756e6374696f6e45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa26469706673582212200773e690657b7c35d2948d65f2937243163c36f036857b909470e784c7396fe064736f6c63430006000033
[ 38 ]
0x60eb4245e3b960ee9c5145a378c1076c4554bcac
pragma solidity 0.6.10; pragma experimental ABIEncoderV2; 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"); } } library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } 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)); } } library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } interface ILocker { /** * @dev Returns the locked amount of untransferable tokens of a given `wallet` */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns the locked amount of untransferable and un-delegatable tokens of a given `wallet`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } 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; } library MathUtils { event UnderflowError( uint a, uint b ); uint constant private _EPS = 1e6; function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Can't reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint newValue = sequence.value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value != newValue) { sequence.value = newValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } function uint2str(uint i) internal pure returns (string memory) { if (i == 0) { return "0"; } uint j = i; uint _i = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len.sub(1); while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } } contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. 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; } contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { 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; } abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } contract ContractManager is OwnableUpgradeSafe { using StringUtils for string; using Address for address; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * Adds actual contract to mapping of actual contract addresses * @param contractsName - contracts name in skale manager system * @param newContractsAddress - contracts address in skale manager system */ function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contracts address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } function getContract(string calldata name) external view returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; require(contractAddress != address(0), name.strConcat(" contract has not been found")); } } contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev allow - throws if called by any account and contract other than the owner * or `contractName` contract * @param contractName - human readable name of contract */ modifier allow(string memory contractName) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.contracts(keccak256(abi.encodePacked(contractName1))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName2))) == msg.sender || contractManager.contracts(keccak256(abi.encodePacked(contractName3))) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } contract Punisher is Permissions, ILocker { /** * @dev Emitted when a slashing condition occurs. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted when a forgive condition occurs. */ event Forgive( address wallet, uint amount ); // holder => tokens mapping (address => uint) private _locked; /** * @dev Executes slashing on a validator and its delegations by an `amount` * of tokens. Currently, SkaleDKG is the only service allowed to execute * slashing. * * Emits a Slash event. * * @param validatorId uint validator to be slashed * @param amount uint slashed amount */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Owner to forgive a slashing condition. * * Emits a Forgive event. * * @param holder address of the slashed * @param amount uint amount to be forgiven */ function forgive(address holder, uint amount) external onlyAdmin { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See ILocker-getAndUpdateLockedAmount */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker-getAndUpdateForbiddenForDelegationAmount */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUserCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Can't add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUserCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } function _totalDelegatedSatisfiesProofOfUserCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } contract TokenState is Permissions, ILocker { /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); string[] private _lockers; /** * @dev Return and update the total locked amount of a given `holder`. * * @param holder address of the token holder * @return total locked amount */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { uint locked = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } return locked; } /** * @dev Return and update the total locked and un-delegatable amount of a given `holder`. * * @param holder address of the token holder * @return amount total slashed amount (non-transferable and non-delegatable) */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a LockerWasRemoved event. * * @param locker string name of contract to remove from locker */ function removeLocker(string calldata locker) external onlyOwner { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a LockerWasAdded event. * * @param locker string name of contract to add to locker */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); event ValidatorWasEnabled( uint validatorId ); event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator Id. * * Requirements: * * - sender must not already have registered a validator Id. * - fee rate must be between 0 - 1000‰. Note: per mille! * * Emits ValidatorRegistered event. * * @param name string * @param description string * @param feeRate uint Fee charged on delegations by the validator per mille * @param minimumDelegationAmount uint Minimum delegation amount accepted by the validator */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate < 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the validator whitelist. Once turned off the * whitelist cannot be re-enabled. */ function disableWhitelist() external onlyOwner { useWhitelist = false; } /** * @dev Allows a validator to request a new address. * * Requirements: * * - new address must not be null * - new address must not be already registered as a validator * * @param newValidatorAddress address */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a given node address. * * Requirements: * * - the given signature must be valid. * - the address must not be assigned to a validator. * * Emits NodeAddressWasAdded event. * * @param nodeAddress address * @param sig bytes signature of validator Id by node operator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a given node address from a validator. * * Emits NodeAddressWasRemoved event. * * @param nodeAddress address */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); _removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. * * @param newName string */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. * * @param newDescription string */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - validator must not have already enabled accepting new requests */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - validator must not have already stopped accepting new requests */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } /** * @dev Returns the amount of validator bond. * * @param validatorId uint ID of validator to return the amount of locked funds * @return bondAmount uint the amount of self-delegated funds by the validator */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns a list of trusted validators. * * @return uint[] trusted validators */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } function checkMinimumDelegation(uint validatorId, uint amount) external view checkValidatorExists(validatorId) allow("DelegationController") returns (bool) { return validators[validatorId].minimumDelegationAmount <= amount ? true : false; } function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function isAuthorizedValidator(uint validatorId) external view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator with given address does not exist"); } function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } // private function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _removeNodeAddress(uint validatorId, address nodeAddress) private { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/8 of Node) uint8 public constant MEDIUM_DIVISOR = 8; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; /** * Set reward and delta periods to new one, run only by owner. This function * only for tests. * @param newRewardPeriod - new Reward period * @param newDeltaPeriod - new Delta period */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * Set new check time. This function only for tests. * @param newCheckTime - new check time */ function setCheckTime(uint newCheckTime) external onlyOwner { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * Set latency new one in ms, run only by owner. This function * only for tests. * @param newAllowableLatency - new Allowable Latency */ function setLatency(uint32 newAllowableLatency) external onlyOwner { allowableLatency = newAllowableLatency; } function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } function setLaunchTimestamp(uint timestamp) external onlyOwner { require(now < launchTimestamp, "Can't set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } function setRotationDelay(uint newDelay) external onlyOwner { rotationDelay = newDelay; } function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; } } contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * @param validatorId uint ID of validator to receive delegation proposal * @param amount uint amount of proposed delegation * @param delegationPeriod uint period of proposed delegation * @param info string extra information provided by the token holder (if any) */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); TokenState tokenState = TokenState(contractManager.getContract("TokenState")); require( validatorService.checkMinimumDelegation(validatorId, amount), "Amount does not meet the validator's minimum delegation amount"); require( validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require( delegationPeriodManager.isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); require( validatorService.isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = skaleToken.balanceOf(msg.sender); uint forbiddenForDelegation = tokenState.getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See ILocker. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See ILocker. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows a token holder to cancel a delegation proposal. * * Requirements: * * - the sender must be the token holder of the delegation proposal. * - the delegation must still be in a PROPOSED state. * * Emits a DelegationRequestCanceledByUser event. * * @param delegationId uint ID of delegation proposal */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a DelegationAccepted event. * * @param delegationId uint ID of delegation proposal */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( validatorService.checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); tokenLaunchLocker.handleDelegationAdd( delegations[delegationId].holder, delegationId, delegations[delegationId].amount, delegations[delegationId].started); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } /** * @dev Allows a delegator to undelegate a specific delegation. * * Requirements: * * - the sender must be the delegator. * - the delegation must be in DELEGATED state. * * Emits an UndelegationRequested event. * * @param delegationId uint ID of delegation to undelegate */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); TokenLaunchLocker tokenLaunchLocker = TokenLaunchLocker(contractManager.getContract("TokenLaunchLocker")); DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); tokenLaunchLocker.handleDelegationRemoving( delegations[delegationId].holder, delegationId, delegations[delegationId].finished); emit UndelegationRequested(delegationId); } /** * @dev Allows the Punisher to confiscate an `amount` of stake from * `validatorId` by slashing. This slashes all delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manger to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * See Punisher. * * Emits a SlashingEvent. * * @param validatorId uint validator to slash * @param amount uint amount to slash * */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); } function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allow("Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function getAndUpdateDelegatedToValidator(uint validatorId, uint month) public allow("Nodes") returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. * * @param delegationId uint ID of the delegation */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); if (_getCurrentMonth() == timeHelpers.timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); require( _lockedInPendingDelegations[holder].month == currentMonth, "There are no delegation requests this month"); require(_lockedInPendingDelegations[holder].amount >= amount, "Unlocking amount is too big"); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); return timeHelpers.getCurrentMonth(); } function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getContract("Punisher")); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { DelegationPeriodManager delegationPeriodManager = DelegationPeriodManager( contractManager.getContract("DelegationPeriodManager")); uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul(delegationPeriodManager.stakeMultipliers( delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < constantsHolder.limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } } contract DelegationPeriodManager is Permissions { /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); mapping (uint => uint) public stakeMultipliers; /** * @dev Creates a new available delegation period and return in the network. * Only the owner may set new delegation period and returns in the network. * * Emits a DelegationPeriodWasSet event. * * @param monthsCount uint delegation duration in months * @param stakeMultiplier uint return for delegation */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner { stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. * * @param monthsCount uint delegation duration in months * @return bool True if delegation period is allowed */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0 ? true : false; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[3] = 100; // 3 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } contract Nodes is Permissions { using SafeCast for uint; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; // informs that Node is created event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, uint time, uint gasSpend ); // informs that node is fully finished quitting from the system event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); // informs that owner starts the procedure of quitting the Node from the system event ExitInited( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } /** * @dev removeSpaceFromFractionalNode - occupies space from Fractional Node * function could be run only by Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be occupied */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev adSpaceToFractionalNode - returns space to Fractional Node * function could be run only be Schains * @param nodeIndex - index of Node at array of Fractional Nodes * @param space - space which should be returned */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allow("Schains") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev changeNodeLastRewardDate - changes Node's last reward date * function could be run only by SkaleManager * @param nodeIndex - index of Node */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev createNode - creates new Node and add it to the Nodes contract * function could be only run by SkaleManager * @param from - owner of Node */ // * @return nodeIndex - index of Node function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name has already registered"); require(params.port > 0, "Port is zero"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, validatorId); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, block.timestamp, gasleft()); } /** * @dev initExit - initiate a procedure of quitting the system * function could be only run by SkaleManager * @param nodeIndex - index of Node * @return true - if everything OK */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { _setNodeLeaving(nodeIndex); emit ExitInited( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev completeExit - finish a procedure of quitting the system * function could be run only by SkaleManager * @param nodeIndex - index of Node * @return amount of SKL which be returned */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); _deleteNode(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); } function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "Validator must meet the Minimum Staking Requirement"); } function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function setNodeInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.In_Maintenance; } function removeNodeFromInMaintenance(uint nodeIndex) external { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintence"); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = getValidatorId(nodeIndex); bool permitted = (_isOwner() || isNodeExist(msg.sender, nodeIndex)); if (!permitted) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodes[nodeIndex].status = NodeStatus.Active; } function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @dev isTimeForReward - checks if time for reward has come * @param nodeIndex - index of Node * @return if time for reward has come - true, else - false */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return uint(nodes[nodeIndex].lastRewardDate).add(constantsHolder.rewardPeriod()) <= block.timestamp; } /** * @dev getNodeIP - get ip address of Node * @param nodeIndex - index of Node * @return ip address */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev getNodePort - get Node's port * @param nodeIndex - index of Node * @return port */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev isNodeLeft - checks if Node status Left * @param nodeIndex - index of Node * @return if Node status Left - true, else - false */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev getNodeLastRewardDate - get Node last reward date * @param nodeIndex - index of Node * @return Node last reward date */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev getNodeNextRewardDate - get Node next reward date * @param nodeIndex - index of Node * @return Node next reward date */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes[nodeIndex].lastRewardDate.add(constantsHolder.rewardPeriod()); } /** * @dev getNumberOfNodes - get number of Nodes * @return number of Nodes */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev getNumberOfFullNodes - get number Online Nodes * @return number of active nodes plus number of leaving nodes */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev getActiveNodeIPs - get array of ips of Active Nodes * @return activeNodeIPs - array of ips of Active Nodes */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev getActiveNodesByAddress - get array of indexes of Active Nodes, which were * created by msg.sender * @return activeNodesByAddress Array of indexes of Active Nodes, which were created by msg.sender */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (nodeIndexes[msg.sender].isNodeExist[indexOfNodes] && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @dev getActiveNodeIds - get array of indexes of Active Nodes * @return activeNodeIds - array of indexes of Active Nodes */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator with such ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach * @param contractsAddress needed in Permissions constructor */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev isNodeExist - checks existence of Node at this address * @param from - account address * @param nodeIndex - index of Node * @return if exist - true, else - false */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev isNodeActive - checks if Node status Active * @param nodeIndex - index of Node * @return if Node status Active - true, else - false */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev isNodeLeaving - checks if Node status Leaving * @param nodeIndex - index of Node * @return if Node status Leaving - true, else - false */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev _setNodeLeft - set Node Left * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; } /** * @dev _setNodeLeaving - set Node Leaving * function could be run only by Nodes * @param nodeIndex - index of Node */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev _addNode - adds Node to array * function could be run only by executor * @param from - owner of Node * @param name - Node name * @param ip - Node ip * @param publicIP - Node public ip * @param port - Node public port * @param publicKey - Ethereum public key * @return nodeIndex Index of Node */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } }
0x608060405234801561001057600080fd5b506004361061035d5760003560e01c806391d14854116101d3578063c34da52411610104578063d12fa445116100a2578063d8f272e11161007c578063d8f272e114610769578063dcbaac601461077c578063dcd3744d1461078f578063f5dc5442146107a45761035d565b8063d12fa4451461073b578063d45025f814610743578063d547741f146107565761035d565b8063c921ba68116100de578063c921ba68146106ef578063c94f9c3d14610702578063c9e91c6614610715578063ca15c873146107285761035d565b8063c34da524146106b6578063c4d66de8146106c9578063c585d604146106dc5761035d565b8063ab4df71e11610171578063b9f452471161014b578063b9f452471461065d578063bb4d53d614610670578063be59bdc114610683578063c1ab2264146106a35761035d565b8063ab4df71e1461063a578063b39e12cf1461064d578063b81c806a146106555761035d565b8063a1a1ca5e116101ad578063a1a1ca5e146105f7578063a217fddf14610617578063a4e692291461061f578063a910ede3146106275761035d565b806391d14854146105be57806396a0be4f146105d15780639bcd9521146105e45761035d565b8063427cd6a6116102ad578063822a56281161024b5780638e001b7c116102255780638e001b7c146105655780639010d07c1461057857806390a98a891461059857806390e848c0146105ab5761035d565b8063822a56281461053757806389f102281461054a5780638d3a0f19146105525761035d565b80636e23e8e5116102875780636e23e8e5146104dd57806370d2fa18146104f057806379fe630814610511578063819cdcd7146105245761035d565b8063427cd6a6146104a45780635990e3cb146104b75780635b6b4185146104ca5761035d565b806321c74e241161031a5780632f2ff15d116102f45780632f2ff15d14610458578063361864641461046b57806336568abe1461047e578063378bb226146104915761035d565b806321c74e241461041057806322ef64fe14610430578063248a9ca3146104455761035d565b806303dd6c271461036257806308e85aab1461038b5780630bdeab23146103a0578063117066eb146103b3578063125a0be2146103d35780631c53c280146103e8575b600080fd5b610375610370366004614ab7565b6107ac565b6040516103829190614dc1565b60405180910390f35b610393610827565b6040516103829190614db8565b6103936103ae3660046149de565b61082d565b6103c66103c1366004614ab7565b610842565b6040516103829190614dad565b6103e66103e13660046149de565b6109bb565b005b6103fb6103f6366004614ab7565b610efd565b60405161038299989796959493929190614dfe565b61042361041e366004614ab7565b610ff1565b60405161038291906154f3565b61043861104a565b6040516103829190614d75565b610393610453366004614ab7565b6110da565b6103e6610466366004614acf565b6110f2565b6103c6610479366004614b1f565b61113a565b6103e661048c366004614acf565b61114f565b61043861049f366004614ab7565b611191565b6103936104b2366004614afe565b611311565b6103c66104c5366004614ab7565b61133f565b6103c66104d8366004614ab7565b61139f565b6103e66104eb366004614ab7565b6113cc565b6105036104fe366004614ab7565b6115a9565b6040516103829291906155bb565b6103c661051f366004614ab7565b6115d8565b6103c6610532366004614b81565b611605565b610393610545366004614ab7565b61189b565b6103936118e8565b6103e6610560366004614ab7565b6118ee565b610393610573366004614ab7565b611a3c565b61058b610586366004614afe565b611b92565b6040516103829190614ceb565b6103936105a6366004614ab7565b611bb9565b6103e66105b9366004614afe565b611bcb565b6103c66105cc366004614acf565b611f16565b6103c66105df366004614ab7565b611f34565b6103c66105f2366004614ab7565b611f49565b61060a610605366004614ab7565b611f76565b6040516103829190614dd6565b610393611fc7565b610393611fcc565b6103c6610635366004614ab7565b611feb565b6103e6610648366004614afe565b61217e565b61058b6122cd565b6103936122dc565b6103e661066b366004614ab7565b6122e2565b6103e661067e366004614a16565b61248d565b610696610691366004614ab7565b6128cf565b6040516103829190614cff565b6103936106b1366004614bc9565b61294d565b6103c66106c4366004614a6c565b612a90565b6103e66106d73660046149de565b612ae3565b6104386106ea366004614bc9565b612b7e565b6103936106fd366004614ab7565b612d58565b6103e6610710366004614b81565b612da5565b6103c6610723366004614afe565b612f10565b610393610736366004614ab7565b6133fa565b610438613411565b610393610751366004614ab7565b6134d2565b6103e6610764366004614acf565b61351f565b610393610777366004614c01565b613559565b6103c661078a366004614ab7565b613572565b6107976136ab565b6040516103829190614d27565b61039361376f565b609854600090829081106107db5760405162461bcd60e51b81526004016107d2906151a1565b60405180910390fd5b60985483106107fc5760405162461bcd60e51b81526004016107d290614f2a565b6098838154811061080957fe5b600091825260209091206009909102016001015460e01b9392505050565b60a15481565b609a6020526000908152604090206001015481565b609854600090829081106108685760405162461bcd60e51b81526004016107d2906151a1565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a373916108b591869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016108e79190614db8565b60206040518083038186803b1580156108ff57600080fd5b505afa158015610913573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061093791906149fa565b6001600160a01b0316148061094f575061094f613775565b61096b5760405162461bcd60e51b81526004016107d290615443565b61097484613781565b7f569d021389e6c8c8854094692650704c835bfd93b13fc0dbb234e7c59be1108b8442425a6040516109a994939291906155a0565b60405180910390a15060019392505050565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a37391610a0891869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401610a3a9190614db8565b60206040518083038186803b158015610a5257600080fd5b505afa158015610a66573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a8a91906149fa565b6001600160a01b03161480610aa25750610aa2613775565b610abe5760405162461bcd60e51b81526004016107d290615443565b609754604051633581777360e01b81526000916001600160a01b031690633581777390610aed9060040161547a565b60206040518083038186803b158015610b0557600080fd5b505afa158015610b19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b3d91906149fa565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610b7190600401615373565b60206040518083038186803b158015610b8957600080fd5b505afa158015610b9d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bc191906149fa565b90506000826001600160a01b031663bad21775866040518263ffffffff1660e01b8152600401610bf19190614ceb565b60206040518083038186803b158015610c0957600080fd5b505afa158015610c1d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c419190614b69565b60405163f93c86f160e01b81529091506001600160a01b0384169063f93c86f190610c70908490600401614db8565b60206040518083038186803b158015610c8857600080fd5b505afa158015610c9c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cc09190614a97565b610cdc5760405162461bcd60e51b81526004016107d2906150db565b6000818152609f6020908152604091829020805483518184028101840190945280845260609392830182828015610d3257602002820191906000526020600020905b815481526020019060010190808311610d1e575b505050505090506000836001600160a01b0316631d703812846040518263ffffffff1660e01b8152600401610d679190614db8565b602060405180830381600087803b158015610d8157600080fd5b505af1158015610d95573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610db99190614b69565b609754604051633581777360e01b81529192506000916001600160a01b0390911690633581777390610ded90600401614fe2565b60206040518083038186803b158015610e0557600080fd5b505afa158015610e19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e3d91906149fa565b6001600160a01b031663ed089aa76040518163ffffffff1660e01b815260040160206040518083038186803b158015610e7557600080fd5b505afa158015610e89573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ead9190614b69565b905081610ed582610ec9600187516137d290919063ffffffff16565b9063ffffffff6137f716565b1115610ef35760405162461bcd60e51b81526004016107d290615088565b5050505050505050565b60988181548110610f0a57fe5b60009182526020918290206009919091020180546040805160026001841615610100026000190190931692909204601f810185900485028301850190915280825291935091839190830182828015610fa35780601f10610f7857610100808354040283529160200191610fa3565b820191906000526020600020905b815481529060010190602001808311610f8657829003601f168201915b5050505060018301546004840154600585015460068601546007870154600890970154959660e085811b97640100000000870490911b9650600160401b90950461ffff169460ff9091169089565b609854600090829081106110175760405162461bcd60e51b81526004016107d2906151a1565b6098838154811061102457fe5b6000918252602090912060099091020160010154600160401b900461ffff169392505050565b606060a05467ffffffffffffffff8111801561106557600080fd5b5060405190808252806020026020018201604052801561108f578160200160208202803683370190505b5090506000805b6098548110156110d5576110a9816115d8565b156110cd57808383815181106110bb57fe5b60209081029190910101526001909101905b600101611096565b505090565b6000818152606560205260409020600201545b919050565b600082815260656020526040902060020154611110906105cc613831565b61112c5760405162461bcd60e51b81526004016107d290614edb565b6111368282613835565b5050565b609b6020526000908152604090205460ff1681565b611157613831565b6001600160a01b0316816001600160a01b0316146111875760405162461bcd60e51b81526004016107d2906154a4565b61113682826138a4565b609754604051633581777360e01b81526060916000916001600160a01b03909116906335817773906111c59060040161547a565b60206040518083038186803b1580156111dd57600080fd5b505afa1580156111f1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061121591906149fa565b604051635be8c60f60e01b81529091506001600160a01b03821690635be8c60f90611244908690600401614db8565b60206040518083038186803b15801561125c57600080fd5b505afa158015611270573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112949190614a97565b6112b05760405162461bcd60e51b81526004016107d2906153a1565b6000838152609f60209081526040918290208054835181840281018401909452808452909183018282801561130457602002820191906000526020600020905b8154815260200190600101908083116112f0575b5050505050915050919050565b609f602052816000526040600020818154811061132a57fe5b90600052602060002001600091509150505481565b609854600090829081106113655760405162461bcd60e51b81526004016107d2906151a1565b60035b6098848154811061137557fe5b600091825260209091206007600990920201015460ff16600381111561139757fe5b149392505050565b609854600090829081106113c55760405162461bcd60e51b81526004016107d2906151a1565b6001611368565b6000609882815481106113db57fe5b600091825260209091206007600990920201015460ff1660038111156113fd57fe5b1461141a5760405162461bcd60e51b81526004016107d290614e6d565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906114499060040161547a565b60206040518083038186803b15801561146157600080fd5b505afa158015611475573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061149991906149fa565b905060006114a68361189b565b905060006114b2613775565b806114c257506114c23385612a90565b90508061154b57604051630ba7341960e11b815282906001600160a01b0385169063174e6832906114f7903390600401614ceb565b60206040518083038186803b15801561150f57600080fd5b505afa158015611523573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115479190614b69565b1490505b806115685760405162461bcd60e51b81526004016107d290615127565b60036098858154811061157757fe5b60009182526020909120600760099092020101805460ff1916600183600381111561159e57fe5b021790555050505050565b609981815481106115b657fe5b60009182526020909120600290910201805460019091015460ff909116915082565b609854600090829081106115fe5760405162461bcd60e51b81526004016107d2906151a1565b6000611368565b6098546000908390811061162b5760405162461bcd60e51b81526004016107d2906151a1565b604080518082018252600c81526b2737b232a937ba30ba34b7b760a11b60208083019190915282518084018452600f81526e14d8da185a5b9cd25b9d195c9b985b608a1b8183015260975493519293909233926001600160a01b039092169163ec56a3739161169c91879101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016116ce9190614db8565b60206040518083038186803b1580156116e657600080fd5b505afa1580156116fa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061171e91906149fa565b6001600160a01b031614806117e1575060975460405133916001600160a01b03169063ec56a37390611754908590602001614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016117869190614db8565b60206040518083038186803b15801561179e57600080fd5b505afa1580156117b2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117d691906149fa565b6001600160a01b0316145b806117ef57506117ef613775565b61180b5760405162461bcd60e51b81526004016107d290615443565b8460ff166099878154811061181c57fe5b600091825260209091206002909102015460ff16101561183f5760009350611892565b60ff85161561188d5761188d866118886118838860ff1660998b8154811061186357fe5b600091825260209091206002909102015460ff169063ffffffff61391316565b613955565b61397c565b600193505b50505092915050565b609854600090829081106118c15760405162461bcd60e51b81526004016107d2906151a1565b609883815481106118ce57fe5b906000526020600020906009020160080154915050919050565b60a25481565b609854819081106119115760405162461bcd60e51b81526004016107d2906151a1565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a3739161195e91869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016119909190614db8565b60206040518083038186803b1580156119a857600080fd5b505afa1580156119bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119e091906149fa565b6001600160a01b031614806119f857506119f8613775565b611a145760405162461bcd60e51b81526004016107d290615443565b4260988481548110611a2257fe5b906000526020600020906009020160050181905550505050565b60985460009082908110611a625760405162461bcd60e51b81526004016107d2906151a1565b609754604051633581777360e01b81526000916001600160a01b031690633581777390611a9190600401614fe2565b60206040518083038186803b158015611aa957600080fd5b505afa158015611abd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ae191906149fa565b9050611b8a816001600160a01b031663e88dc5b76040518163ffffffff1660e01b815260040160206040518083038186803b158015611b1f57600080fd5b505afa158015611b33573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b579190614ba5565b63ffffffff1660988681548110611b6a57fe5b9060005260206000209060090201600501546137d290919063ffffffff16565b949350505050565b6000828152606560205260408120611bb0908363ffffffff613b8c16565b90505b92915050565b609d6020526000908152604090205481565b60985481908110611bee5760405162461bcd60e51b81526004016107d2906151a1565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a37391611c3b91869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401611c6d9190614db8565b60206040518083038186803b158015611c8557600080fd5b505afa158015611c99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611cbd91906149fa565b6001600160a01b03161480611cd55750611cd5613775565b611cf15760405162461bcd60e51b81526004016107d290615443565b609754604051633581777360e01b81526000916001600160a01b031690633581777390611d209060040161547a565b60206040518083038186803b158015611d3857600080fd5b505afa158015611d4c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d7091906149fa565b604051635be8c60f60e01b81529091506001600160a01b03821690635be8c60f90611d9f908890600401614db8565b60206040518083038186803b158015611db757600080fd5b505afa158015611dcb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611def9190614a97565b611e0b5760405162461bcd60e51b81526004016107d2906153a1565b6000858152609f6020908152604091829020805483518184028101840190945280845260609392830182828015611e6157602002820191906000526020600020905b815481526020019060010190808311611e4d575b505050505090506000611e748287613b98565b90508151811015611ee0576000878152609f602052604090208251611ea090600163ffffffff61391316565b81548110611eaa57fe5b9060005260206000200154609f60008981526020019081526020016000208281548110611ed357fe5b6000918252602090912001555b6000878152609f60205260409020805480611ef757fe5b6001900381819060005260206000200160009055905550505050505050565b6000828152606560205260408120611bb0908363ffffffff613bd816565b609c6020526000908152604090205460ff1681565b60985460009082908110611f6f5760405162461bcd60e51b81526004016107d2906151a1565b6002611368565b60985460009082908110611f9c5760405162461bcd60e51b81526004016107d2906151a1565b60988381548110611fa957fe5b600091825260209091206009909102016007015460ff169392505050565b600081565b6000611fe560a15460a0546137d290919063ffffffff16565b90505b90565b609854600090829081106120115760405162461bcd60e51b81526004016107d2906151a1565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a3739161205e91869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016120909190614db8565b60206040518083038186803b1580156120a857600080fd5b505afa1580156120bc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906120e091906149fa565b6001600160a01b031614806120f857506120f8613775565b6121145760405162461bcd60e51b81526004016107d290615443565b61211d8461139f565b6121395760405162461bcd60e51b81526004016107d290615174565b61214284613bed565b61214b84613dad565b7f07903541c5c6f3b94d75bbe8eba01679f00857bb87e7d2c2b5eb36fcab0e20a684425a6040516109a99392919061558a565b609854829081106121a15760405162461bcd60e51b81526004016107d2906151a1565b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a373916121ee91869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b81526004016122209190614db8565b60206040518083038186803b15801561223857600080fd5b505afa15801561224c573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061227091906149fa565b6001600160a01b031614806122885750612288613775565b6122a45760405162461bcd60e51b81526004016107d290615443565b82609885815481106122b257fe5b90600052602060002090600902016006018190555050505050565b6097546001600160a01b031681565b60985490565b6003609882815481106122f157fe5b600091825260209091206007600990920201015460ff16600381111561231357fe5b146123305760405162461bcd60e51b81526004016107d2906151e4565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061235f9060040161547a565b60206040518083038186803b15801561237757600080fd5b505afa15801561238b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123af91906149fa565b905060006123bc8361189b565b905060006123c8613775565b806123d857506123d83385612a90565b90508061246157604051630ba7341960e11b815282906001600160a01b0385169063174e68329061240d903390600401614ceb565b60206040518083038186803b15801561242557600080fd5b505afa158015612439573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061245d9190614b69565b1490505b8061247e5760405162461bcd60e51b81526004016107d290615127565b60006098858154811061157757fe5b604080518082018252600c81526b29b5b0b632a6b0b730b3b2b960a11b6020808301919091526097549251919233926001600160a01b039091169163ec56a373916124da91869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b815260040161250c9190614db8565b60206040518083038186803b15801561252457600080fd5b505afa158015612538573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061255c91906149fa565b6001600160a01b031614806125745750612574613775565b6125905760405162461bcd60e51b81526004016107d290615443565b6125a06040830160208401614b1f565b6001600160e01b031916158015906125e75750609b60006125c76040850160208601614b1f565b6001600160e01b031916815260208101919091526040016000205460ff16155b6126035760405162461bcd60e51b81526004016107d290614f9c565b609c600061261184806155ce565b604051602001612622929190614c52565b60408051601f198184030181529181528151602092830120835290820192909252016000205460ff16156126685760405162461bcd60e51b81526004016107d2906153e6565b600061267a6080840160608501614b47565b61ffff161161269b5760405162461bcd60e51b81526004016107d29061541d565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906126ca9060040161547a565b60206040518083038186803b1580156126e257600080fd5b505afa1580156126f6573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061271a91906149fa565b6001600160a01b031663bad21775856040518263ffffffff1660e01b81526004016127459190614ceb565b60206040518083038186803b15801561275d57600080fd5b505afa158015612771573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127959190614b69565b90506000612839856127a786806155ce565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152506127ec925050506040880160208901614b1f565b6127fc6060890160408a01614b1f565b61280c60808a0160608b01614b47565b6040805180820182529060808c019060029083908390808284376000920191909152508a9150613f719050565b90507f1af6b8442f2c99735a0286ab2f8e6ac963401b07d10ebc79cd9805fdd37986cc818661286887806155ce565b61287860408a0160208b01614b1f565b61288860608b0160408c01614b1f565b61289860808c0160608d01614b47565b6128a860e08d0160c08e01614b47565b425a6040516128c09a99989796959493929190615502565b60405180910390a15050505050565b6128d76148ff565b609854829081106128fa5760405162461bcd60e51b81526004016107d2906151a1565b6098838154811061290757fe5b60009182526020918290206040805180820191829052600990930290910160028181018054855293949092916003019085018083116112f0575050505050915050919050565b609754604051633581777360e01b815260009182916001600160a01b039091169063358177739061298090600401614fe2565b60206040518083038186803b15801561299857600080fd5b505afa1580156129ac573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129d091906149fa565b9050600091506000816001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b158015612a1157600080fd5b505afa158015612a25573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612a499190614be5565b60ff169050835b818160ff1611612a885760ff81166000908152609e6020526040902054612a7e90859063ffffffff6137d216565b9350600101612a50565b505050919050565b60985460009082908110612ab65760405162461bcd60e51b81526004016107d2906151a1565b50506001600160a01b03919091166000908152609a60209081526040808320938352929052205460ff1690565b600054610100900460ff1680612afc5750612afc6144c5565b80612b0a575060005460ff16155b612b265760405162461bcd60e51b81526004016107d2906152e3565b600054610100900460ff16158015612b51576000805460ff1961ff0019909116610100171660011790555b612b5a826144cb565b600060a081905560a181905560a2558015611136576000805461ff00191690555050565b609754604051633581777360e01b81526060916000916001600160a01b0390911690633581777390612bb290600401614fe2565b60206040518083038186803b158015612bca57600080fd5b505afa158015612bde573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612c0291906149fa565b90506060612c0f8461294d565b67ffffffffffffffff81118015612c2557600080fd5b50604051908082528060200260200182016040528015612c4f578160200160208202803683370190505b50905060008090506000836001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b158015612c9257600080fd5b505afa158015612ca6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612cca9190614be5565b60ff169050855b818160ff1611612d4d5760005b60ff82166000908152609e6020526040902054811015612d445760ff82166000908152609e60205260409020805482908110612d1657fe5b9060005260206000200154858581518110612d2d57fe5b602090810291909101015260019384019301612cde565b50600101612cd1565b509195945050505050565b60985460009082908110612d7e5760405162461bcd60e51b81526004016107d2906151a1565b60988381548110612d8b57fe5b906000526020600020906009020160050154915050919050565b60985482908110612dc85760405162461bcd60e51b81526004016107d2906151a1565b604080518082018252600781526653636861696e7360c81b6020808301919091526097549251919233926001600160a01b039091169163ec56a37391612e1091869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401612e429190614db8565b60206040518083038186803b158015612e5a57600080fd5b505afa158015612e6e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e9291906149fa565b6001600160a01b03161480612eaa5750612eaa613775565b612ec65760405162461bcd60e51b81526004016107d290615443565b60ff831615612f0a57612f0a846118886118838660ff1660998981548110612eea57fe5b600091825260209091206002909102015460ff169063ffffffff6137d216565b50505050565b60985460009082908110612f365760405162461bcd60e51b81526004016107d2906151a1565b6040805180820182526006815265426f756e747960d01b6020808301919091526097549251919233926001600160a01b039091169163ec56a37391612f7d91869101614c62565b604051602081830303815290604052805190602001206040518263ffffffff1660e01b8152600401612faf9190614db8565b60206040518083038186803b158015612fc757600080fd5b505afa158015612fdb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612fff91906149fa565b6001600160a01b031614806130175750613017613775565b6130335760405162461bcd60e51b81526004016107d290615443565b609754604051633581777360e01b81526000916001600160a01b03169063358177739061306290600401615373565b60206040518083038186803b15801561307a57600080fd5b505afa15801561308e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130b291906149fa565b609754604051633581777360e01b81529192506000916001600160a01b03909116906335817773906130e69060040161547a565b60206040518083038186803b1580156130fe57600080fd5b505afa158015613112573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061313691906149fa565b604051635be8c60f60e01b81529091506001600160a01b03821690635be8c60f90613165908a90600401614db8565b60206040518083038186803b15801561317d57600080fd5b505afa158015613191573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131b59190614a97565b6131d15760405162461bcd60e51b81526004016107d2906153a1565b6000878152609f602090815260409182902080548351818402810184019094528084526060939283018282801561322757602002820191906000526020600020905b815481526020019060010190808311613213575b50505050509050600061323a8289613b98565b90508151811061325c5760405162461bcd60e51b81526004016107d290615042565b604051630eb81c0960e11b81526000906001600160a01b03861690631d7038129061328b908d90600401614db8565b602060405180830381600087803b1580156132a557600080fd5b505af11580156132b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132dd9190614b69565b609754604051633581777360e01b81529192506000916001600160a01b039091169063358177739061331190600401614fe2565b60206040518083038186803b15801561332957600080fd5b505afa15801561333d573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061336191906149fa565b6001600160a01b031663ed089aa76040518163ffffffff1660e01b815260040160206040518083038186803b15801561339957600080fd5b505afa1580156133ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133d19190614b69565b9050816133e982610ec986600163ffffffff6137d216565b11159b9a5050505050505050505050565b6000818152606560205260408120611bb39061456a565b336000908152609a602052604090206001015460609067ffffffffffffffff8111801561343d57600080fd5b50604051908082528060200260200182016040528015613467578160200160208202803683370190505b5090506000805b6098548110156110d557336000908152609a6020908152604080832084845290915290205460ff1680156134a657506134a6816115d8565b156134ca57808383815181106134b857fe5b60209081029190910101526001909101905b60010161346e565b609854600090829081106134f85760405162461bcd60e51b81526004016107d2906151a1565b6098838154811061350557fe5b906000526020600020906009020160060154915050919050565b60008281526065602052604090206002015461353d906105cc613831565b6111875760405162461bcd60e51b81526004016107d29061521b565b609e602052816000526040600020818154811061132a57fe5b609854600090829081106135985760405162461bcd60e51b81526004016107d2906151a1565b609754604051633581777360e01b81526000916001600160a01b0316906335817773906135c790600401614fe2565b60206040518083038186803b1580156135df57600080fd5b505afa1580156135f3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061361791906149fa565b9050426136a1826001600160a01b031663e88dc5b76040518163ffffffff1660e01b815260040160206040518083038186803b15801561365657600080fd5b505afa15801561366a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061368e9190614ba5565b63ffffffff1660988781548110611b6a57fe5b1115949350505050565b606060a05467ffffffffffffffff811180156136c657600080fd5b506040519080825280602002602001820160405280156136f0578160200160208202803683370190505b5090506000805b6098548110156110d55761370a816115d8565b15613767576098818154811061371c57fe5b906000526020600020906009020160010160009054906101000a900460e01b83838151811061374757fe5b6001600160e01b0319909216602092830291909101909101526001909101905b6001016136f7565b60a05481565b6000611fe58133611f16565b60016098828154811061379057fe5b60009182526020909120600760099092020101805460ff191660018360038111156137b757fe5b02179055505060a0805460001901905560a180546001019055565b600082820183811015611bb05760405162461bcd60e51b81526004016107d29061500b565b60008261380657506000611bb3565b8282028284828161381357fe5b0414611bb05760405162461bcd60e51b81526004016107d29061526b565b3390565b6000828152606560205260409020613853908263ffffffff61457516565b1561113657613860613831565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526065602052604090206138c2908263ffffffff61458a16565b15611136576138cf613831565b6001600160a01b0316816001600160a01b0316837ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b60405160405180910390a45050565b6000611bb083836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061459f565b600061010082106139785760405162461bcd60e51b81526004016107d290614f57565b5090565b60006099838154811061398b57fe5b600091825260208220600290910201546099805460ff909216935090859081106139b157fe5b60009182526020808320600160029093020182015460ff86168452609e9091526040909220549192506139ea919063ffffffff61391316565b811015613ac15760ff82166000908152609e602052604081208054613a1690600163ffffffff61391316565b81548110613a2057fe5b9060005260206000200154905080609e60008560ff1660ff1681526020019081526020016000208381548110613a5257fe5b90600052602060002001819055508160998281548110613a6e57fe5b906000526020600020906002020160010181905550609e60008460ff1660ff168152602001908152602001600020805480613aa557fe5b6001900381819060005260206000200160009055905550613af3565b60ff82166000908152609e60205260409020805480613adc57fe5b600190038181906000526020600020016000905590555b60ff83166000908152609e60209081526040822080546001810182559083529120018490556099805484919086908110613b2957fe5b60009182526020808320600292909202909101805460ff191660ff9485161790559185168152609e9091526040902054613b64906001613913565b60998581548110613b7157fe5b90600052602060002090600202016001018190555050505050565b6000611bb083836145cb565b6000805b8351811015613bcf5782848281518110613bb257fe5b60200260200101511415613bc7579050611bb3565b600101613b9c565b50509051919050565b6000611bb0836001600160a01b038416614610565b6000609b600060988481548110613c0057fe5b600091825260208083206009929092029091016001015460e01b6001600160e01b03191683528201929092526040018120805460ff19169215159290921790915560988054609c91839185908110613c5457fe5b9060005260206000209060090201600001604051602001613c759190614c7e565b60405160208183030381529060405280519060200120815260200190815260200160002060006101000a81548160ff021916908315150217905550609d600060988381548110613cc157fe5b9060005260206000209060090201600001604051602001613ce29190614c7e565b6040516020818303038152906040528051906020012081526020019081526020016000206000905560006003811115613d1757fe5b60988281548110613d2457fe5b600091825260209091206007600990920201015460ff166003811115613d4657fe5b1415613d5b5760a08054600019019055613d66565b60a180546000190190555b600260988281548110613d7557fe5b60009182526020909120600760099092020101805460ff19166001836003811115613d9c57fe5b02179055505060a280546001019055565b600060998281548110613dbc57fe5b600091825260208220600290910201546099805460ff90921693509084908110613de257fe5b60009182526020808320600160029093020182015460ff86168452609e909152604090922054919250613e1b919063ffffffff61391316565b811015613ef25760ff82166000908152609e602052604081208054613e4790600163ffffffff61391316565b81548110613e5157fe5b9060005260206000200154905080609e60008560ff1660ff1681526020019081526020016000208381548110613e8357fe5b90600052602060002001819055508160998281548110613e9f57fe5b906000526020600020906002020160010181905550609e60008460ff1660ff168152602001908152602001600020805480613ed657fe5b6001900381819060005260206000200160009055905550613f24565b60ff82166000908152609e60205260409020805480613f0d57fe5b600190038181906000526020600020016000905590555b60998381548110613f3157fe5b60009182526020909120600290910201805460ff191690556099805484908110613f5757fe5b906000526020600020906002020160010160009055505050565b609754604051633581777360e01b815260009182916001600160a01b0390911690633581777390613fa490600401614fe2565b60206040518083038186803b158015613fbc57600080fd5b505afa158015613fd0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613ff491906149fa565b905060986040518061014001604052808a8152602001896001600160e01b0319168152602001886001600160e01b03191681526020018761ffff168152602001868152602001438152602001428152602001600081526020016000600381111561405a57fe5b8152602090810186905282546001810184556000938452928190208251805193946009029091019261408f928492019061491d565b5060208201516001820180546040850151606086015161ffff16600160401b0269ffff00000000000000001960e092831c6401000000000267ffffffff00000000199690931c63ffffffff199094169390931794909416171691909117905560808201516141039060028084019190614997565b5060a0820151600482015560c0820151600582015560e0820151600682015561010082015160078201805460ff1916600183600381111561414057fe5b0217905550610120919091015160089091015560985461416790600163ffffffff61391316565b6000848152609f6020908152604080832080546001810182559084528284200184905551929450909161419c918b9101614c62565b6040516020818303038152906040528051906020012090506001609b60008a6001600160e01b0319166001600160e01b031916815260200190815260200160002060006101000a81548160ff0219169083151502179055506001609c600083815260200190815260200160002060006101000a81548160ff02191690831515021790555082609d6000838152602001908152602001600020819055506001609a60008c6001600160a01b03166001600160a01b03168152602001908152602001600020600001600085815260200190815260200160002060006101000a81548160ff021916908315150217905550609a60008b6001600160a01b03166001600160a01b031681526020019081526020016000206001016000815480929190600101919050555060996040518060400160405280846001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b15801561430857600080fd5b505afa15801561431c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906143409190614be5565b60ff168152602001609e6000866001600160a01b031663c83ee0b36040518163ffffffff1660e01b815260040160206040518083038186803b15801561438557600080fd5b505afa158015614399573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906143bd9190614be5565b60ff908116825260208083019390935260409182016000908120549094528554600180820188559685528385208651600290920201805460ff191691909216178155938201519390940192909255825163c83ee0b360e01b81529251609e9391926001600160a01b0387169263c83ee0b39260048083019392829003018186803b15801561444a57600080fd5b505afa15801561445e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144829190614be5565b60ff16815260208082019290925260400160009081208054600181810183559183529290912090910184905560a080549091019055509098975050505050505050565b303b1590565b600054610100900460ff16806144e457506144e46144c5565b806144f2575060005460ff16155b61450e5760405162461bcd60e51b81526004016107d2906152e3565b600054610100900460ff16158015614539576000805460ff1961ff0019909116610100171660011790555b614541614628565b61454c60003361112c565b614555826146bb565b8015611136576000805461ff00191690555050565b6000611bb382614731565b6000611bb0836001600160a01b038416614735565b6000611bb0836001600160a01b03841661477f565b600081848411156145c35760405162461bcd60e51b81526004016107d29190614deb565b505050900390565b815460009082106145ee5760405162461bcd60e51b81526004016107d290614e99565b8260000182815481106145fd57fe5b9060005260206000200154905092915050565b60009081526001919091016020526040902054151590565b600054610100900460ff168061464157506146416144c5565b8061464f575060005460ff16155b61466b5760405162461bcd60e51b81526004016107d2906152e3565b600054610100900460ff16158015614696576000805460ff1961ff0019909116610100171660011790555b61469e614845565b6146a6614845565b80156146b8576000805461ff00191690555b50565b6001600160a01b0381166146e15760405162461bcd60e51b81526004016107d290615331565b6146f3816001600160a01b03166148c6565b61470f5760405162461bcd60e51b81526004016107d2906152ac565b609780546001600160a01b0319166001600160a01b0392909216919091179055565b5490565b60006147418383614610565b61477757508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155611bb3565b506000611bb3565b6000818152600183016020526040812054801561483b57835460001980830191908101906000908790839081106147b257fe5b90600052602060002001549050808760000184815481106147cf57fe5b6000918252602080832090910192909255828152600189810190925260409020908401905586548790806147ff57fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050611bb3565b6000915050611bb3565b600054610100900460ff168061485e575061485e6144c5565b8061486c575060005460ff16155b6148885760405162461bcd60e51b81526004016107d2906152e3565b600054610100900460ff161580156146a6576000805460ff1961ff00199091166101001716600117905580156146b8576000805461ff001916905550565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611b8a575050151592915050565b60405180604001604052806002906020820280368337509192915050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061495e57805160ff191683800117855561498b565b8280016001018555821561498b579182015b8281111561498b578251825591602001919060010190614970565b506139789291506149c4565b826002810192821561498b579160200282018281111561498b578251825591602001919060010190614970565b611fe891905b8082111561397857600081556001016149ca565b6000602082840312156149ef578081fd5b8135611bb081615653565b600060208284031215614a0b578081fd5b8151611bb081615653565b60008060408385031215614a28578081fd5b8235614a3381615653565b9150602083013567ffffffffffffffff811115614a4e578182fd5b80840160e08187031215614a60578283fd5b80925050509250929050565b60008060408385031215614a7e578182fd5b8235614a8981615653565b946020939093013593505050565b600060208284031215614aa8578081fd5b81518015158114611bb0578182fd5b600060208284031215614ac8578081fd5b5035919050565b60008060408385031215614ae1578182fd5b823591506020830135614af381615653565b809150509250929050565b60008060408385031215614b10578182fd5b50508035926020909101359150565b600060208284031215614b30578081fd5b81356001600160e01b031981168114611bb0578182fd5b600060208284031215614b58578081fd5b813561ffff81168114611bb0578182fd5b600060208284031215614b7a578081fd5b5051919050565b60008060408385031215614b93578182fd5b823591506020830135614af381615668565b600060208284031215614bb6578081fd5b815163ffffffff81168114611bb0578182fd5b600060208284031215614bda578081fd5b8135611bb081615668565b600060208284031215614bf6578081fd5b8151611bb081615668565b60008060408385031215614c13578182fd5b8235614a8981615668565b60008151808452614c36816020860160208601615627565b601f01601f19169290920160200192915050565b61ffff169052565b6000828483379101908152919050565b60008251614c74818460208701615627565b9190910192915050565b6000808354600180821660008114614c9d5760018114614cb457612d4d565b60ff198316865260028304607f1686019350612d4d565b600283048786526020808720875b83811015614cdb5781548a820152908501908201614cc2565b5050509095019695505050505050565b6001600160a01b0391909116815260200190565b60408101818360005b6002811015611892578151835260209283019290910190600101614d08565b6020808252825182820181905260009190848201906040850190845b81811015614d695783516001600160e01b03191683529284019291840191600101614d43565b50909695505050505050565b6020808252825182820181905260009190848201906040850190845b81811015614d6957835183529284019291840191600101614d91565b901515815260200190565b90815260200190565b6001600160e01b031991909116815260200190565b60208101614de38361561c565b825292915050565b600060208252611bb06020830184614c1e565b6000610120808352614e128184018d614c1e565b91505063ffffffff60e01b808b166020840152808a1660408401525061ffff881660608301528660808301528560a08301528460c0830152614e538461561c565b60e0830152826101008301529a9950505050505050505050565b6020808252601290820152714e6f6465206973206e6f742041637469766560701b604082015260600190565b60208082526022908201527f456e756d657261626c655365743a20696e646578206f7574206f6620626f756e604082015261647360f01b606082015260800190565b6020808252602f908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526e0818591b5a5b881d1bc819dc985b9d608a1b606082015260800190565b602080825260139082015272139bd91948191bd95cc81b9bdd08195e1a5cdd606a1b604082015260600190565b60208082526025908201527f53616665436173743a2076616c756520646f65736e27742066697420696e2038604082015264206269747360d81b606082015260800190565b60208082526026908201527f49502061646472657373206973207a65726f206f72206973206e6f7420617661604082015265696c61626c6560d01b606082015260800190565b6020808252600f908201526e21b7b739ba30b73a39a437b63232b960891b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526026908201527f4e6f646520646f6573206e6f7420657869737420666f7220746869732056616c60408201526534b230ba37b960d11b606082015260800190565b60208082526033908201527f56616c696461746f72206d757374206d65657420746865204d696e696d756d2060408201527214dd185ada5b99c814995c5d5a5c995b595b9d606a1b606082015260800190565b6020808252602c908201527f56616c696461746f72206973206e6f7420617574686f72697a656420746f206360408201526b72656174652061206e6f646560a01b606082015260800190565b6020808252602d908201527f53656e646572206973206e6f74207065726d697474656420746f2063616c6c2060408201526c3a3434b990333ab731ba34b7b760991b606082015260800190565b6020808252601390820152724e6f6465206973206e6f74204c656176696e6760681b604082015260600190565b60208082526023908201527f4e6f64652077697468207375636820696e64657820646f6573206e6f742065786040820152621a5cdd60ea1b606082015260800190565b60208082526018908201527f4e6f6465206973206e6f7420496e204d61696e74656e63650000000000000000604082015260600190565b60208082526030908201527f416363657373436f6e74726f6c3a2073656e646572206d75737420626520616e60408201526f2061646d696e20746f207265766f6b6560801b606082015260800190565b60208082526021908201527f536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f6040820152607760f81b606082015260800190565b60208082526017908201527f41646472657373206973206e6f7420636f6e7472616374000000000000000000604082015260600190565b6020808252602e908201527f436f6e747261637420696e7374616e63652068617320616c726561647920626560408201526d195b881a5b9a5d1a585b1a5e995960921b606082015260800190565b60208082526022908201527f436f6e74726163744d616e616765722061646472657373206973206e6f742073604082015261195d60f21b606082015260800190565b6020808252601490820152732232b632b3b0ba34b7b721b7b73a3937b63632b960611b604082015260600190565b60208082526025908201527f56616c696461746f722077697468207375636820494420646f6573206e6f7420604082015264195e1a5cdd60da1b606082015260800190565b6020808252601b908201527f4e616d652068617320616c726561647920726567697374657265640000000000604082015260600190565b6020808252600c908201526b506f7274206973207a65726f60a01b604082015260600190565b60208082526019908201527f4d6573736167652073656e64657220697320696e76616c696400000000000000604082015260600190565b60208082526010908201526f56616c696461746f725365727669636560801b604082015260600190565b6020808252602f908201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560408201526e103937b632b9903337b91039b2b63360891b606082015260800190565b61ffff91909116815260200190565b8a81526001600160a01b038a1660208201526101206040820181905281018890526000610140898b82850137828a018101919091526001600160e01b031988811660608401528716608083015261ffff861660a0830152601f8901601f191682010161557160c0830186614c4a565b60e0820193909352610100015298975050505050505050565b9283526020830191909152604082015260600190565b93845260208401929092526040830152606082015260800190565b60ff929092168252602082015260400190565b6000808335601e198436030181126155e4578283fd5b8084018035925067ffffffffffffffff8311156155ff578384fd5b6020019250503681900382131561561557600080fd5b9250929050565b80600481106110ed57fe5b60005b8381101561564257818101518382015260200161562a565b83811115612f0a5750506000910152565b6001600160a01b03811681146146b857600080fd5b60ff811681146146b857600080fdfea2646970667358221220cb84951cb25c1b757967e5a2151f0655eb45d6064510c4dc85d52d877e61b99b64736f6c634300060a0033
[ 6, 4, 9, 7 ]
0x6154Cb64Db010c7f77B152A861059719D567DFA0
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 999900000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); // fetch all needed data // using LTV as tokenLiquidationThreshold (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLiquidationThreshold,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLiquidationThreshold,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLiquidationThreshold); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return totalCollateralETH; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLiquidationThreshold, totalCollateralETH), wmul(tokenLiquidationThreshold, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLiquidationThreshold)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLiquidationThreshold) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice), NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice), NINETY_NINE_PERCENT_WEI); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_wrappers, rates); } } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] < _rates[minIndex]) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x019739e288973F92bDD3c1d87178E206E51fd911; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Faucet { function gulp(address) public virtual; } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public view virtual returns(uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { // address public constant ETH_FLIPPER = 0xd8a04F5412223F513DC55F839574430f5EC15531; // address public constant BAT_FLIPPER = 0xaA745404d55f88C108A28c86abE7b5A1E7817c07; // address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; // address public constant ETH_JOIN = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; // address public constant BAT_JOIN = 0x3D0B1912B66114d4096F48A8CEe3A56C231772cA; // bytes32 public constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; // bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; // address public constant SAVER_EXCHANGE = 0x606e9758a39d2d7fA7e70BC68E6E7D9b02948962; // function daiBid(uint _bidId, bool _isEth, uint _amount) public { // uint tendAmount = _amount * (10 ** 27); // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // joinDai(_amount); // (, uint lot, , , , , , ) = Flipper(flipper).bids(_bidId); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).tend(_bidId, lot, tendAmount); // } // function collateralBid(uint _bidId, bool _isEth, uint _amount) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // uint bid; // (bid, , , , , , , ) = Flipper(flipper).bids(_bidId); // joinDai(bid / (10**27)); // Vat(VAT_ADDRESS).hope(flipper); // Flipper(flipper).dent(_bidId, _amount, bid); // } // function closeBid(uint _bidId, bool _isEth) public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // Flipper(flipper).deal(_bidId); // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function closeBidAndExchange( // uint _bidId, // bool _isEth, // uint256[4] memory _data, // address _exchangeAddress, // bytes memory _callData // ) // public { // address flipper = _isEth ? ETH_FLIPPER : BAT_FLIPPER; // address join = _isEth ? ETH_JOIN : BAT_JOIN; // (uint bidAmount, , , , , , , ) = Flipper(flipper).bids(_bidId); // Flipper(flipper).deal(_bidId); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(address(this), (bidAmount / 10**27)); // address srcToken = _isEth ? KYBER_ETH_ADDRESS : address(Gem(join).gem()); // uint daiAmount = swap( // _data, // srcToken, // DAI_ADDRESS, // _exchangeAddress, // _callData // ); // ERC20(DAI_ADDRESS).transfer(msg.sender, daiAmount); // } // function exitCollateral(bool _isEth) public { // address join = _isEth ? ETH_JOIN : BAT_JOIN; // bytes32 ilk = _isEth ? ETH_ILK : BAT_ILK; // uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); // Vat(VAT_ADDRESS).hope(join); // Gem(join).exit(msg.sender, amount); // } // function exitDai() public { // uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // Vat(VAT_ADDRESS).hope(DAI_JOIN); // Gem(DAI_JOIN).exit(msg.sender, amount); // } // function withdrawToken(address _token) public { // uint balance = ERC20(_token).balanceOf(address(this)); // ERC20(_token).transfer(msg.sender, balance); // } // function withdrawEth() public { // uint balance = address(this).balance; // msg.sender.transfer(balance); // } // function joinDai(uint _amount) internal { // uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); // if (_amount > amountInVat) { // uint amountDiff = (_amount - amountInVat) + 1; // ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); // ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); // Join(DAI_JOIN).join(address(this), amountDiff); // } // } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { address payable public constant MCD_CREATE_FLASH_LOAN = 0xb09bCc172050fBd4562da8b229Cf3E45Dc3045A6; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).transferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).transfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract ManagerLike { function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint wad) public { GemLike(gem).transfer(dst, wad); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract LoanShifterTaker is AdminAuth, ProxyPermission { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_loanShift, _exchangeData); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory _exchangeData ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); uint loanAmount = _loanShift.debtAmount; if (_loanShift.wholeDebt) { loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), loanAmount, paramsData); removePermission(loanShifterReceiverAddr); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } 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) { // 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) { 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; if (_wholeDebt) { (,amount,,,,,,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 price; bool usageAsCollateralEnabled; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]), totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { approvedCallers[msg.sender] = true; aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_MONITOR_PROXY = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x9D266997bc73B27d4302E711b55FD78B5278e1De; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); address payable payableProxy = payable(proxy); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payableProxy).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy uint256 collateralAmount = ERC20(aCollateralToken).balanceOf(user); ERC20(aCollateralToken).safeTransferFrom(user, proxy, collateralAmount); // enable as collateral DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateral(address)", collateralToken)); // withdraw deposited eth DSProxy(payableProxy).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x56AC1EFC17ecDe083889520137B0cfb30d2cF384; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 80000000000; // 80 gwei uint public REPAY_GAS_COST = 2200000; uint public BOOST_GAS_COST = 1700000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { approvedCallers[msg.sender] = true; compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, address(this).balance, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, address(this).balance, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr); } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2 { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_srcAddr, _destAddr, _destAmount); uint256 srcAmount = wmul(_destAmount, srcRate); rate = getSellRate(_destAddr, _srcAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == KYBER_ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2 { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { address srcAddr = ethToWethAddr(_srcAddr); if (srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(srcAddr).safeTransfer(msg.sender, ERC20(srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2 { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { if (_srcAddr == WETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { approvedCallers[msg.sender] = true; monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai }); address collAddr = closeCDP(closeData, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); sendLeftover(collAddr, DAI_ADDRESS, tx.origin); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData ) internal returns (address) { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; address user = DSProxy(payable(_closeData.proxy)).owner(); if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, user); } else { dfsFee = getFee(_closeData.daiAmount, user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = address(Join(_closeData.joinAddr).gem()); require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); return tokenAddr; } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address payable public constant MCD_CLOSE_FLASH_LOAN = 0xdFccc9C59c7361307d47c558ffA75840B32DbA29; address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData ) public payable { MCD_CLOSE_FLASH_LOAN.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(MCD_CLOSE_FLASH_LOAN, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, MCD_CLOSE_FLASH_LOAN, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { Join(_joinAddr).gem().approve(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } Join(_joinAddr).gem().approve(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); if (maxDebt >= _exchangeData.srcAmount) { boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); if (maxColl >= _exchangeData.srcAmount) { repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x988B6CFBf3332FF98FFBdED665b1F53a61f92612); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); // if (paramData.swapType == 1) { // COLL_SWAP // exchangeData.srcAmount = getBalance(exchangeData.srcAddr); // (, uint amount) = _sell(exchangeData); // sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); // } else if (paramData.swapType == 2) { // DEBT_SWAP // exchangeData.destAmount = (_amount + _fee); // _buy(exchangeData); // } else { // NO_SWAP just send tokens to proxy // sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); // } // // Execute the Open operation (Skip if it's debt swap) // if (paramData.swapType != 2) { // DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // } // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM proxyData1 = abi.encodeWithSignature( "close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } // Call specific function if it's a debt swap if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]); } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getWholeDebt(uint _cdpId, address _joinAddr) public virtual returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); // draw coll if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) { uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this)); require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0); } else { require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); } // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); uint256 maxCollateral = getMaxCollateral(_data.srcAddr, address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); IAToken(aTokenCollateral).redeem(_data.srcAmount); // swap (, uint256 destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); uint256 maxBorrow = getMaxBorrow(_data.srcAddr, address(this)); _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, VARIABLE_RATE, AAVE_REFERRAL_CODE); _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, uint256 destAmount) = _sell(_data); if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (address payable proxyAddr, bytes memory proxyData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); // Swap (, uint sellAmount) = _sell(exchangeData); // DFS fee getFee(sellAmount, exchangeData.destAddr, proxyAddr); // Send amount to DSProxy sendToProxy(proxyAddr, exchangeData.destAddr); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(compOpenProxy, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (address payable, bytes memory proxyData, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); return (payable(proxy), proxyData, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x6423708d6B84Af237Ab309dF49f6b8Fb751f28FB; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xBD3140131dEd4426694257411d564791Cc36D382; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); if (_exData.srcAmount <= maxColl) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); if (_exData.srcAmount <= maxBorrow) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } }
0x6080604052600436106102515760003560e01c80637753f47b11610139578063b20b7209116100b6578063deca5f881161007a578063deca5f8814610643578063e3bbb4f114610663578063eef21cd214610678578063f05def8114610698578063f24ccbfe146106b8578063f851a440146106cd57610251565b8063b20b7209146105c4578063bfc36172146105d9578063bfe142a3146105f9578063c91d59fe1461060e578063d98bb5b11461062357610251565b80638da5cb5b116100fd5780638da5cb5b1461052d578063a56f971814610542578063a71975af14610557578063a7304bf714610584578063a8c90323146105a457610251565b80637753f47b146104c657806379521f02146104db5780637b925ab1146104f05780637f9ad5d614610505578063870e44d91461051857610251565b80633816377e116101d257806349a3d7371161019657806349a3d7371461041c5780634d3f199e1461043c57806350c86de51461045c57806351c4a63114610471578063696806c014610491578063747293fb146104a657610251565b80633816377e1461039d57806339df1878146103bd5780633a128322146103d257806341c0e1b5146103f2578063441697521461040757610251565b80631ec18ec0116102195780631ec18ec0146103065780632a56f602146103265780632b6e6581146103465780632b8f40071461036657806336fc603f1461038857610251565b806305a363de1461025657806306d5e37e14610281578063087b0286146102af57806318bf60e1146102c45780631e48907b146102e6575b600080fd5b34801561026257600080fd5b5061026b6106e2565b6040516102789190612698565b60405180910390f35b34801561028d57600080fd5b506102a161029c3660046120e4565b6106e7565b60405161027892919061255a565b6102c26102bd36600461218e565b6108b5565b005b3480156102d057600080fd5b506102d9610b77565b60405161027891906126a7565b3480156102f257600080fd5b506102c2610301366004611fed565b610b7d565b34801561031257600080fd5b506102d9610321366004612025565b610bb6565b34801561033257600080fd5b506102d9610341366004612282565b610df9565b34801561035257600080fd5b506102d9610361366004612025565b610e23565b34801561037257600080fd5b5061037b6112f6565b6040516102789190612430565b34801561039457600080fd5b506102d9611305565b3480156103a957600080fd5b506102c26103b8366004612282565b61130b565b3480156103c957600080fd5b5061037b611338565b3480156103de57600080fd5b506102c26103ed36600461209d565b611350565b3480156103fe57600080fd5b506102c26113ef565b34801561041357600080fd5b5061037b611414565b34801561042857600080fd5b506102c2610437366004612025565b61142c565b34801561044857600080fd5b506102c2610457366004612282565b6114e2565b34801561046857600080fd5b506102d961150d565b34801561047d57600080fd5b506102c261048c36600461205d565b611513565b34801561049d57600080fd5b506102d9611593565b3480156104b257600080fd5b506102c26104c1366004611fed565b611599565b3480156104d257600080fd5b5061037b6115d4565b3480156104e757600080fd5b5061037b6115ec565b3480156104fc57600080fd5b5061037b6115fb565b6102c261051336600461218e565b611613565b34801561052457600080fd5b506102d9611899565b34801561053957600080fd5b5061037b6118a5565b34801561054e57600080fd5b506102d96118b4565b34801561056357600080fd5b50610577610572366004611fed565b6118ba565b604051610278919061254f565b34801561059057600080fd5b506102c261059f366004611fed565b6118cf565b3480156105b057600080fd5b506102c26105bf366004612282565b611908565b3480156105d057600080fd5b5061037b611933565b3480156105e557600080fd5b506102a16105f43660046120e4565b611942565b34801561060557600080fd5b5061037b611a41565b34801561061a57600080fd5b5061037b611a59565b34801561062f57600080fd5b506102d961063e366004611fed565b611a6c565b34801561064f57600080fd5b506102c261065e366004611fed565b611b9c565b34801561066f57600080fd5b506102d9611bc9565b34801561068457600080fd5b506102c2610693366004611fed565b611bcf565b3480156106a457600080fd5b506102c26106b33660046122b2565b611c07565b3480156106c457600080fd5b5061037b611c34565b3480156106d957600080fd5b5061037b611c43565b604081565b600854604051632e4aba1f60e21b8152600091829182916001600160a01b03169063b92ae87c9061071c908790600401612430565b60206040518083038186803b15801561073457600080fd5b505afa158015610748573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061076c91906120c8565b9050610776611f2d565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d4906107a6908890600401612430565b60c06040518083038186803b1580156107be57600080fd5b505afa1580156107d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107f69190612104565b90508161080c5750600092508291506108ae9050565b600086600181111561081a57fe5b14801561082957508060a00151155b1561083d5750600092508291506108ae9050565b600061084886611a6c565b9050600187600181111561085857fe5b141561087a576020909101516001600160801b03168110935091506108ae9050565b600087600181111561088857fe5b14156108aa576040909101516001600160801b03168111935091506108ae9050565b5050505b9250929050565b336000908152600b602052604090205460ff166108d157600080fd5b6003546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190610908903090600401612430565b60206040518083038186803b15801561092057600080fd5b505afa158015610934573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610958919061229a565b106109e35760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f39061098f9084906004016126a7565b602060405180830381600087803b1580156109a957600080fd5b505af11580156109bd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109e191906120c8565b505b6000806109f16000856106e7565b91509150816109ff57600080fd5b6000610a0c600654610df9565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a92911690610a41908c9088906024016125fe565b60408051601f198184030181529181526020820180516001600160e01b03166378e810b160e11b1790525160e086901b6001600160e01b0319168152610a8c9392919060040161245e565b6000604051808303818588803b158015610aa557600080fd5b505af1158015610ab9573d6000803e3d6000fd5b5050505050600080610acc600088611942565b9150915081610ada57600080fd5b610ae2611c52565b600a546040516001600160a01b039091169063d061ce509030908a90610b0e90899087906020016126b0565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b3b939291906124e0565b600060405180830381600087803b158015610b5557600080fd5b505af1158015610b69573d6000803e3d6000fd5b505050505050505050505050565b60065481565b6001546001600160a01b03163314610b9457600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015610c0657600080fd5b505afa158015610c1a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c3e9190612009565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610c8f57600080fd5b505afa158015610ca3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cc79190612009565b90506000826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401610cf79190612430565b6101006040518083038186803b158015610d1057600080fd5b505afa158015610d24573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d48919061237f565b5050509450505050506000826001600160a01b031663b3596f07886040518263ffffffff1660e01b8152600401610d7f9190612430565b60206040518083038186803b158015610d9757600080fd5b505afa158015610dab573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dcf919061229a565b9050610dec610dde8383611c88565b670de05bc096e9c000611cb9565b9450505050505b92915050565b6000806004543a1115610e0e57600454610e10565b3a5b9050610e1c8184611ce1565b9392505050565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316632f58b80d6040518163ffffffff1660e01b815260040160206040518083038186803b158015610e7357600080fd5b505afa158015610e87573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610eab9190612009565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663ed6ff7606040518163ffffffff1660e01b815260040160206040518083038186803b158015610efc57600080fd5b505afa158015610f10573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f349190612009565b905060007324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b031663fca513a86040518163ffffffff1660e01b815260040160206040518083038186803b158015610f8557600080fd5b505afa158015610f99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fbd9190612009565b90506000806000856001600160a01b0316632c6d0e9b896040518263ffffffff1660e01b8152600401610ff09190612430565b6101006040518083038186803b15801561100957600080fd5b505afa15801561101d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110419190612316565b50505094505093509350506000856001600160a01b0316635fc526ff8b6040518263ffffffff1660e01b815260040161107a9190612430565b60806040518083038186803b15801561109257600080fd5b505afa1580156110a6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ca91906122d6565b50509150506000856001600160a01b031663b3596f078c6040518263ffffffff1660e01b81526004016110fd9190612430565b60206040518083038186803b15801561111557600080fd5b505afa158015611129573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061114d919061229a565b90506000876001600160a01b03166318a4dbca8d8d6040518363ffffffff1660e01b815260040161117f929190612444565b60206040518083038186803b15801561119757600080fd5b505afa1580156111ab573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111cf919061229a565b905060006111dd8284611cb9565b9050856111f557509850610df3975050505050505050565b600061121d611217611207888b611ce1565b6112128a6064611ce1565b611d05565b87611d15565b905081811161122c578061122e565b815b905087811061124a57879b505050505050505050505050610df3565b6000611263611259888b611cb9565b6112128886611cb9565b905060006112956112868361128161127b8888611d05565b8b611cb9565b611d20565b6112908c86611d05565b611c88565b9050878110156112d4576112c06112ba6112af838d611ce1565b6112128c6064611ce1565b82611d15565b92508383116112cf57826112d1565b835b92505b6112e1610dde8488611c88565b9d505050505050505050505050505092915050565b6009546001600160a01b031681565b60055481565b6000546001600160a01b0316331461132257600080fd5b64746a528800811061133357600080fd5b600455565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000546001600160a01b0316331461136757600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b03831614156113cb57600080546040516001600160a01b039091169183156108fc02918491818181858888f193505050501580156113c5573d6000803e3d6000fd5b506113eb565b6000546113eb906001600160a01b0384811691168363ffffffff611d3016565b5050565b6000546001600160a01b0316331461140657600080fd5b6000546001600160a01b0316ff5b73322d58b9e75a6918f7e7849aee0ff09369977e0881565b6001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee14156114615761145c828247611513565b6113eb565b6113eb8282846001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016114929190612430565b60206040518083038186803b1580156114aa57600080fd5b505afa1580156114be573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061048c919061229a565b6000546001600160a01b031633146114f957600080fd5b622dc6c0811061150857600080fd5b600555565b61019081565b6001600160a01b03831673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1415611574576040516001600160a01b0383169082156108fc029083906000818181858888f1935050505015801561156e573d6000803e3d6000fd5b5061158e565b61158e6001600160a01b038416838363ffffffff611d3016565b505050565b60035481565b6000546001600160a01b031633146115b057600080fd5b6001600160a01b03166000908152600b60205260409020805460ff19166001179055565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b6008546001600160a01b031681565b731b14e8d511c9a4395425314f849bd737baf8208f81565b336000908152600b602052604090205460ff1661162f57600080fd5b6002546040516370a0823160e01b815281906eb3f879cb30fe243b4dfee438691c04906370a0823190611666903090600401612430565b60206040518083038186803b15801561167e57600080fd5b505afa158015611692573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116b6919061229a565b106117415760405163d8ccd0f360e01b81526eb3f879cb30fe243b4dfee438691c049063d8ccd0f3906116ed9084906004016126a7565b602060405180830381600087803b15801561170757600080fd5b505af115801561171b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061173f91906120c8565b505b60008061174f6001856106e7565b915091508161175d57600080fd5b600061176a600554610df9565b6007546009546040519293506001600160a01b0391821692638a0e833f9234928a9291169061179f908c9088906024016125fe565b60408051601f198184030181529181526020820180516001600160e01b0316633a84827360e11b1790525160e086901b6001600160e01b03191681526117ea9392919060040161245e565b6000604051808303818588803b15801561180357600080fd5b505af1158015611817573d6000803e3d6000fd5b505050505060008061182a600188611942565b915091508161183857600080fd5b611840611c52565b600a546040516001600160a01b039091169063d061ce509030908a9061186c90899087906020016126b0565b6040516020818303038152906040526040518463ffffffff1660e01b8152600401610b3b9392919061248a565b670de05bc096e9c00081565b6000546001600160a01b031681565b60025481565b600b6020526000908152604090205460ff1681565b6001546001600160a01b031633146118e657600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b0316331461191f57600080fd5b622dc6c0811061192e57600080fd5b600655565b6007546001600160a01b031681565b60008061194d611f2d565b60085460405163335d71f560e21b81526001600160a01b039091169063cd75c7d49061197d908790600401612430565b60c06040518083038186803b15801561199557600080fd5b505afa1580156119a9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119cd9190612104565b905060006119da85611a6c565b905060018660018111156119ea57fe5b1415611a0a576040909101516001600160801b03168110925090506108ae565b6000866001811115611a1857fe5b1415611a38576020909101516001600160801b03168111925090506108ae565b50509250929050565b7324a42fd28c976a61df5d00d0599c34c4f90748c881565b6eb3f879cb30fe243b4dfee438691c0481565b6000807324a42fd28c976a61df5d00d0599c34c4f90748c86001600160a01b0316630261bf8b6040518163ffffffff1660e01b815260040160206040518083038186803b158015611abc57600080fd5b505afa158015611ad0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611af49190612009565b9050600080826001600160a01b031663bf92857c866040518263ffffffff1660e01b8152600401611b259190612430565b6101006040518083038186803b158015611b3e57600080fd5b505afa158015611b52573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b76919061237f565b50505094505093505050611b93611b8d8383611d20565b83611c88565b95945050505050565b6000546001600160a01b03163314611bb357600080fd5b6001546001600160a01b0316156118e657600080fd5b60045481565b6000546001600160a01b03163314611be657600080fd5b6001600160a01b03166000908152600b60205260409020805460ff19169055565b6000546001600160a01b03163314611c1e57600080fd5b8015611c2e5760028290556113eb565b50600355565b600a546001600160a01b031681565b6001546001600160a01b031681565b4715611c865760405133904780156108fc02916000818181858888f19350505050158015611c84573d6000803e3d6000fd5b505b565b600081611caa611ca085670de0b6b3a7640000611ce1565b6002855b04611d20565b81611cb157fe5b049392505050565b6000670de0b6b3a7640000611caa611cd18585611ce1565b6002670de0b6b3a7640000611ca4565b6000811580611cfc57505080820282828281611cf957fe5b04145b610df357600080fd5b80820382811115610df357600080fd5b6000818381611cb157fe5b80820182811015610df357600080fd5b61158e8363a9059cbb60e01b8484604051602401611d4f929190612536565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526060611dd6826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316611e199092919063ffffffff16565b80519091501561158e5780806020019051810190611df491906120c8565b61158e5760405162461bcd60e51b8152600401611e10906125b4565b60405180910390fd5b6060611e288484600085611e30565b949350505050565b6060611e3b85611ef4565b611e575760405162461bcd60e51b8152600401611e109061257d565b60006060866001600160a01b03168587604051611e749190612414565b60006040518083038185875af1925050503d8060008114611eb1576040519150601f19603f3d011682016040523d82523d6000602084013e611eb6565b606091505b50915091508115611eca579150611e289050565b805115611eda5780518082602001fd5b8360405162461bcd60e51b8152600401611e10919061256a565b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590611e28575050151592915050565b6040805160c081018252600080825260208201819052918101829052606081018290526080810182905260a081019190915290565b8035610df381612715565b600082601f830112611f7d578081fd5b813567ffffffffffffffff811115611f93578182fd5b611fa6601f8201601f19166020016126be565b9150808252836020828501011115611fbd57600080fd5b8060208401602084013760009082016020015292915050565b80516001600160801b0381168114610df357600080fd5b600060208284031215611ffe578081fd5b8135610e1c81612715565b60006020828403121561201a578081fd5b8151610e1c81612715565b60008060408385031215612037578081fd5b823561204281612715565b9150602083013561205281612715565b809150509250929050565b600080600060608486031215612071578081fd5b833561207c81612715565b9250602084013561208c81612715565b929592945050506040919091013590565b600080604083850312156120af578182fd5b82356120ba81612715565b946020939093013593505050565b6000602082840312156120d9578081fd5b8151610e1c8161272a565b600080604083850312156120f6578182fd5b823560028110612042578283fd5b600060c08284031215612115578081fd5b61211f60c06126be565b825161212a81612715565b81526121398460208501611fd6565b602082015261214b8460408501611fd6565b604082015261215d8460608501611fd6565b606082015261216f8460808501611fd6565b608082015260a08301516121828161272a565b60a08201529392505050565b600080604083850312156121a0578182fd5b823567ffffffffffffffff808211156121b7578384fd5b6101209185018087038313156121cb578485fd5b6121d4836126be565b6121de8883611f62565b81526121ed8860208401611f62565b602082015260408201356040820152606082013560608201526080820135608082015261221d8860a08401611f62565b60a082015261222f8860c08401611f62565b60c082015260e0820135935082841115612247578586fd5b61225388858401611f6d565b60e082015261010093508382013584820152809550505050506122798460208501611f62565b90509250929050565b600060208284031215612293578081fd5b5035919050565b6000602082840312156122ab578081fd5b5051919050565b600080604083850312156122c4578182fd5b8235915060208301356120528161272a565b600080600080608085870312156122eb578182fd5b845193506020850151925060408501519150606085015161230b8161272a565b939692955090935050565b600080600080600080600080610100898b031215612332578586fd5b885197506020890151965060408901519550606089015194506080890151935060a0890151925060c0890151915060e089015161236e8161272a565b809150509295985092959890939650565b600080600080600080600080610100898b03121561239b578182fd5b505086516020880151604089015160608a015160808b015160a08c015160c08d015160e0909d0151959e949d50929b919a50985090965094509092509050565b6001600160a01b03169052565b600081518084526124008160208601602086016126e5565b601f01601f19169290920160200192915050565b600082516124268184602087016126e5565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152606060408201819052600090611b93908301846123e8565b6001600160a01b03848116825283166020820152608060408201819052601290820152714175746f6d6174696341617665526570617960701b60a082015260c060608201819052600090611b93908301846123e8565b6001600160a01b0384811682528316602082015260806040820181905260129082015271105d5d1bdb585d1a58d0585d99509bdbdcdd60721b60a082015260c060608201819052600090611b93908301846123e8565b6001600160a01b03929092168252602082015260400190565b901515815260200190565b9115158252602082015260400190565b600060208252610e1c60208301846123e8565b6020808252601d908201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604082015260600190565b6020808252602a908201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6040820152691bdd081cdd58d8d9595960b21b606082015260800190565b6000604082526126126040830185516123db565b602084015161262460608401826123db565b5060408401516080830152606084015160a0830152608084015160c083015260a084015161265560e08401826123db565b5060c084015161010061266a818501836123db565b60e08601516101208581015291506126866101608501836123e8565b95015161014084015250506020015290565b61ffff91909116815260200190565b90815260200190565b918252602082015260400190565b60405181810167ffffffffffffffff811182821017156126dd57600080fd5b604052919050565b60005b838110156127005781810151838201526020016126e8565b8381111561270f576000848401525b50505050565b6001600160a01b0381168114611c8457600080fd5b8015158114611c8457600080fdfea2646970667358221220d8c474ff426a96eeab3a3a97354c059b55060082cc4e7f88f1ba9fd1d8133f7b64736f6c63430006060033
[ 37, 17, 11, 8, 9, 12, 16, 5, 2 ]
0x61cb5d28c57b1a4e4b010498ffa922be60baa73f
pragma solidity 0.4.21; contract EIP20Interface { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract AlcToken is EIP20Interface { uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public allowed; string public name; uint8 public decimals; string public symbol; function AlcToken( uint256 _initialAmount, string _tokenName, uint8 _decimalUnits, string _tokenSymbol ) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; name = _tokenName; decimals = _decimalUnits; symbol = _tokenSymbol; } function transfer(address _to, uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; balances[_to] += _value; emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(balances[_from] >= _value && allowance >= _value); balances[_to] += _value; balances[_from] -= _value; if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } }
0x6060604052600436106100af576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100b4578063095ea7b31461014257806318160ddd1461019c57806323b872dd146101c557806327e235e31461023e578063313ce5671461028b5780635c658165146102ba57806370a082311461032657806395d89b4114610373578063a9059cbb14610401578063dd62ed3e1461045b575b600080fd5b34156100bf57600080fd5b6100c76104c7565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101075780820151818401526020810190506100ec565b50505050905090810190601f1680156101345780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561014d57600080fd5b610182600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610565565b604051808215151515815260200191505060405180910390f35b34156101a757600080fd5b6101af610657565b6040518082815260200191505060405180910390f35b34156101d057600080fd5b610224600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803590602001909190505061065d565b604051808215151515815260200191505060405180910390f35b341561024957600080fd5b610275600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919050506108f7565b6040518082815260200191505060405180910390f35b341561029657600080fd5b61029e61090f565b604051808260ff1660ff16815260200191505060405180910390f35b34156102c557600080fd5b610310600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610922565b6040518082815260200191505060405180910390f35b341561033157600080fd5b61035d600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610947565b6040518082815260200191505060405180910390f35b341561037e57600080fd5b610386610990565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156103c65780820151818401526020810190506103ab565b50505050905090810190601f1680156103f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561040c57600080fd5b610441600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610a2e565b604051808215151515815260200191505060405180910390f35b341561046657600080fd5b6104b1600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610b87565b6040518082815260200191505060405180910390f35b60038054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561055d5780601f106105325761010080835404028352916020019161055d565b820191906000526020600020905b81548152906001019060200180831161054057829003601f168201915b505050505081565b600081600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905092915050565b60005481565b600080600260008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015801561072e5750828110155b151561073957600080fd5b82600160008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555082600160008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156108865782600260008773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055505b8373ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef856040518082815260200191505060405180910390a360019150509392505050565b60016020528060005260406000206000915090505481565b600460009054906101000a900460ff1681565b6002602052816000526040600020602052806000526040600020600091509150505481565b6000600160008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b60058054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610a265780601f106109fb57610100808354040283529160200191610a26565b820191906000526020600020905b815481529060010190602001808311610a0957829003601f168201915b505050505081565b600081600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610a7e57600080fd5b81600160003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905092915050565b6000600260008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050929150505600a165627a7a72305820a0809a4966ade322b8a6a6b7177e7f5644b9ed9eb5b1e52fee6e913dbadb44e40029
[ 38 ]
0x628F645A5A6D36fDE852b906ef18d38A128ed7d1
pragma solidity 0.6.5; pragma experimental ABIEncoderV2; contract ERC20SubToken { // TODO add natspec, currently blocked by solidity compiler issue event Transfer(address indexed from, address indexed to, uint256 value); // TODO add natspec, currently blocked by solidity compiler issue event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice A descriptive name for the tokens /// @return name of the tokens function name() public view returns (string memory) { return _name; } /// @notice An abbreviated name for the tokens /// @return symbol of the tokens function symbol() public view returns (string memory) { return _symbol; } /// @notice the tokenId in ERC20Group /// @return the tokenId in ERC20Group function groupTokenId() external view returns (uint256) { return _index; } /// @notice the ERC20Group address /// @return the address of the group function groupAddress() external view returns (address) { return address(_group); } function totalSupply() external view returns (uint256) { return _group.supplyOf(_index); } function balanceOf(address who) external view returns (uint256) { return _group.balanceOf(who, _index); } function decimals() external pure returns (uint8) { return uint8(0); } function transfer(address to, uint256 amount) external returns (bool success) { _transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) external returns (bool success) { if (msg.sender != from && !_group.isAuthorizedToTransfer(from, msg.sender)) { uint256 allowance = _mAllowed[from][msg.sender]; if (allowance != ~uint256(0)) { // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717) require(allowance >= amount, "NOT_AUTHOIZED_ALLOWANCE"); _mAllowed[from][msg.sender] = allowance - amount; } } _transfer(from, to, amount); return true; } function approve(address spender, uint256 amount) external returns (bool success) { _approveFor(msg.sender, spender, amount); return true; } function approveFor( address from, address spender, uint256 amount ) external returns (bool success) { require(msg.sender == from || _group.isAuthorizedToApprove(msg.sender), "NOT_AUTHORIZED"); _approveFor(from, spender, amount); return true; } function emitTransferEvent( address from, address to, uint256 amount ) external { require(msg.sender == address(_group), "NOT_AUTHORIZED_GROUP_ONLY"); emit Transfer(from, to, amount); } // /////////////////// INTERNAL //////////////////////// function _approveFor( address owner, address spender, uint256 amount ) internal { require(owner != address(0) && spender != address(0), "INVALID_FROM_OR_SPENDER"); _mAllowed[owner][spender] = amount; emit Approval(owner, spender, amount); } function allowance(address owner, address spender) external view returns (uint256 remaining) { return _mAllowed[owner][spender]; } function _transfer( address from, address to, uint256 amount ) internal { _group.singleTransferFrom(from, to, _index, amount); } // ///////////////////// UTILITIES /////////////////////// using SafeMathWithRequire for uint256; // //////////////////// CONSTRUCTOR ///////////////////// constructor( ERC20Group group, uint256 index, string memory tokenName, string memory tokenSymbol ) public { _group = group; _index = index; _name = tokenName; _symbol = tokenSymbol; } // ////////////////////// DATA /////////////////////////// ERC20Group internal immutable _group; uint256 internal immutable _index; mapping(address => mapping(address => uint256)) internal _mAllowed; string internal _name; string internal _symbol; } interface CatalystValue { struct GemEvent { uint256[] gemIds; bytes32 blockHash; } function getValues( uint256 catalystId, uint256 seed, GemEvent[] calldata events, uint32 totalNumberOfGemTypes ) external view returns (uint32[] memory values); } contract Admin { address internal _admin; /// @dev emitted when the contract administrator is changed. /// @param oldAdmin address of the previous administrator. /// @param newAdmin address of the new administrator. event AdminChanged(address oldAdmin, address newAdmin); /// @dev gives the current administrator of this contract. /// @return the current administrator of this contract. function getAdmin() external view returns (address) { return _admin; } /// @dev change the administrator to be `newAdmin`. /// @param newAdmin address of the new administrator. function changeAdmin(address newAdmin) external { require(msg.sender == _admin, "only admin can change admin"); emit AdminChanged(_admin, newAdmin); _admin = newAdmin; } modifier onlyAdmin() { require(msg.sender == _admin, "only admin allowed"); _; } } contract MetaTransactionReceiver is Admin { mapping(address => bool) internal _metaTransactionContracts; /// @dev emiited when a meta transaction processor is enabled/disabled /// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights. /// @param enabled set whether the metaTransactionProcessor is enabled or disabled. event MetaTransactionProcessor(address metaTransactionProcessor, bool enabled); /// @dev Enable or disable the ability of `metaTransactionProcessor` to perform meta-tx (metaTransactionProcessor rights). /// @param metaTransactionProcessor address that will be given/removed metaTransactionProcessor rights. /// @param enabled set whether the metaTransactionProcessor is enabled or disabled. function setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) public { require(msg.sender == _admin, "only admin can setup metaTransactionProcessors"); _setMetaTransactionProcessor(metaTransactionProcessor, enabled); } function _setMetaTransactionProcessor(address metaTransactionProcessor, bool enabled) internal { _metaTransactionContracts[metaTransactionProcessor] = enabled; emit MetaTransactionProcessor(metaTransactionProcessor, enabled); } /// @dev check whether address `who` is given meta-transaction execution rights. /// @param who The address to query. /// @return whether the address has meta-transaction execution rights. function isMetaTransactionProcessor(address who) external view returns (bool) { return _metaTransactionContracts[who]; } } contract SuperOperators is Admin { mapping(address => bool) internal _superOperators; event SuperOperator(address superOperator, bool enabled); /// @notice Enable or disable the ability of `superOperator` to transfer tokens of all (superOperator rights). /// @param superOperator address that will be given/removed superOperator right. /// @param enabled set whether the superOperator is enabled or disabled. function setSuperOperator(address superOperator, bool enabled) external { require(msg.sender == _admin, "only admin is allowed to add super operators"); _superOperators[superOperator] = enabled; emit SuperOperator(superOperator, enabled); } /// @notice check whether address `who` is given superOperator rights. /// @param who The address to query. /// @return whether the address has superOperator rights. function isSuperOperator(address who) public view returns (bool) { return _superOperators[who]; } } interface ERC20 { /// @notice emitted when tokens are transfered from one address to another. /// @param from address from which the token are transfered from (zero means tokens are minted). /// @param to destination address which the token are transfered to (zero means tokens are burnt). /// @param value amount of tokens transferred. event Transfer(address indexed from, address indexed to, uint256 value); /// @notice emitted when owner grant transfer rights to another address /// @param owner address allowing its token to be transferred. /// @param spender address allowed to spend on behalf of `owner` /// @param value amount of tokens allowed. event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice return the current total amount of tokens owned by all holders. /// @return supply total number of tokens held. function totalSupply() external view returns (uint256 supply); /// @notice return the number of tokens held by a particular address. /// @param who address being queried. /// @return balance number of token held by that address. function balanceOf(address who) external view returns (uint256 balance); /// @notice transfer tokens to a specific address. /// @param to destination address receiving the tokens. /// @param value number of tokens to transfer. /// @return success whether the transfer succeeded. function transfer(address to, uint256 value) external returns (bool success); /// @notice transfer tokens from one address to another. /// @param from address tokens will be sent from. /// @param to destination address receiving the tokens. /// @param value number of tokens to transfer. /// @return success whether the transfer succeeded. function transferFrom( address from, address to, uint256 value ) external returns (bool success); /// @notice approve an address to spend on your behalf. /// @param spender address entitled to transfer on your behalf. /// @param value amount allowed to be transfered. /// @param success whether the approval succeeded. function approve(address spender, uint256 value) external returns (bool success); /// @notice return the current allowance for a particular owner/spender pair. /// @param owner address allowing spender. /// @param spender address allowed to spend. /// @return amount number of tokens `spender` can spend on behalf of `owner`. function allowance(address owner, address spender) external view returns (uint256 amount); } interface Medianizer { function read() external view returns (bytes32); } library AddressUtils { function toPayable(address _address) internal pure returns (address payable _payable) { return address(uint160(_address)); } function isContract(address addr) internal view returns (bool) { // for accounts without code, i.e. `keccak256('')`: bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; bytes32 codehash; // solium-disable-next-line security/no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != accountHash); } } library BytesUtil { function memcpy( uint256 dest, uint256 src, uint256 len ) internal pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint256 mask = 256**(32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function pointerToBytes(uint256 src, uint256 len) internal pure returns (bytes memory) { bytes memory ret = new bytes(len); uint256 retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, src, len); return ret; } function addressToBytes(address a) internal pure returns (bytes memory b) { assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a)) mstore(0x40, add(m, 52)) b := m } } function uint256ToBytes(uint256 a) internal pure returns (bytes memory b) { assembly { let m := mload(0x40) mstore(add(m, 32), a) mstore(0x40, add(m, 64)) b := m } } function doFirstParamEqualsAddress(bytes memory data, address _address) internal pure returns (bool) { if (data.length < (36 + 32)) { return false; } uint256 value; assembly { value := mload(add(data, 36)) } return value == uint256(_address); } function doParamEqualsUInt256( bytes memory data, uint256 i, uint256 value ) internal pure returns (bool) { if (data.length < (36 + (i + 1) * 32)) { return false; } uint256 offset = 36 + i * 32; uint256 valuePresent; assembly { valuePresent := mload(add(data, offset)) } return valuePresent == value; } function overrideFirst32BytesWithAddress(bytes memory data, address _address) internal pure returns (bytes memory) { uint256 dest; assembly { dest := add(data, 48) } // 48 = 32 (offset) + 4 (func sig) + 12 (address is only 20 bytes) bytes memory addressBytes = addressToBytes(_address); uint256 src; assembly { src := add(addressBytes, 32) } memcpy(dest, src, 20); return data; } function overrideFirstTwo32BytesWithAddressAndInt( bytes memory data, address _address, uint256 _value ) internal pure returns (bytes memory) { uint256 dest; uint256 src; assembly { dest := add(data, 48) } // 48 = 32 (offset) + 4 (func sig) + 12 (address is only 20 bytes) bytes memory bbytes = addressToBytes(_address); assembly { src := add(bbytes, 32) } memcpy(dest, src, 20); assembly { dest := add(data, 68) } // 48 = 32 (offset) + 4 (func sig) + 32 (next slot) bbytes = uint256ToBytes(_value); assembly { src := add(bbytes, 32) } memcpy(dest, src, 32); return data; } } library ObjectLib32 { using SafeMathWithRequire for uint256; enum Operations {ADD, SUB, REPLACE} // Constants regarding bin or chunk sizes for balance packing uint256 constant TYPES_BITS_SIZE = 32; // Max size of each object uint256 constant TYPES_PER_UINT256 = 256 / TYPES_BITS_SIZE; // Number of types per uint256 // // Objects and Tokens Functions // /** * @dev Return the bin number and index within that bin where ID is * @param tokenId Object type * @return bin Bin number * @return index ID's index within that bin */ function getTokenBinIndex(uint256 tokenId) internal pure returns (uint256 bin, uint256 index) { bin = (tokenId * TYPES_BITS_SIZE) / 256; index = tokenId % TYPES_PER_UINT256; return (bin, index); } /** * @dev update the balance of a type provided in binBalances * @param binBalances Uint256 containing the balances of objects * @param index Index of the object in the provided bin * @param amount Value to update the type balance * @param operation Which operation to conduct : * Operations.REPLACE : Replace type balance with amount * Operations.ADD : ADD amount to type balance * Operations.SUB : Substract amount from type balance */ function updateTokenBalance( uint256 binBalances, uint256 index, uint256 amount, Operations operation ) internal pure returns (uint256 newBinBalance) { uint256 objectBalance = 0; if (operation == Operations.ADD) { objectBalance = getValueInBin(binBalances, index); newBinBalance = writeValueInBin(binBalances, index, objectBalance.add(amount)); } else if (operation == Operations.SUB) { objectBalance = getValueInBin(binBalances, index); require(objectBalance >= amount, "can't substract more than there is"); newBinBalance = writeValueInBin(binBalances, index, objectBalance.sub(amount)); } else if (operation == Operations.REPLACE) { newBinBalance = writeValueInBin(binBalances, index, amount); } else { revert("Invalid operation"); // Bad operation } return newBinBalance; } /* * @dev return value in binValue at position index * @param binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param index index at which to retrieve value * @return Value at given index in bin */ function getValueInBin(uint256 binValue, uint256 index) internal pure returns (uint256) { // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 rightShift = 256 - TYPES_BITS_SIZE * (index + 1); return (binValue >> rightShift) & mask; } /** * @dev return the updated binValue after writing amount at index * @param binValue uint256 containing the balances of TYPES_PER_UINT256 types * @param index Index at which to retrieve value * @param amount Value to store at index in bin * @return Value at given index in bin */ function writeValueInBin( uint256 binValue, uint256 index, uint256 amount ) internal pure returns (uint256) { require(amount < 2**TYPES_BITS_SIZE, "Amount to write in bin is too large"); // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << TYPES_BITS_SIZE) - 1; // Shift amount uint256 leftShift = 256 - TYPES_BITS_SIZE * (index + 1); return (binValue & ~(mask << leftShift)) | (amount << leftShift); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } library SafeMathWithRequire { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; require(c / a == b, "overflow"); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "divbyzero"); // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "undeflow"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "overflow"); return c; } } library SigUtil { function recover(bytes32 hash, bytes memory sig) internal pure returns (address recovered) { require(sig.length == 65); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } require(v == 27 || v == 28); recovered = ecrecover(hash, v, r, s); require(recovered != address(0)); } function recoverWithZeroOnFailure(bytes32 hash, bytes memory sig) internal pure returns (address) { if (sig.length != 65) { return (address(0)); } bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } // Builds a prefixed hash to mimic the behavior of eth_sign. function prefixed(bytes32 hash) internal pure returns (bytes memory) { return abi.encodePacked("\x19Ethereum Signed Message:\n32", hash); } } contract ERC20Group is SuperOperators, MetaTransactionReceiver { uint256 internal constant MAX_UINT256 = ~uint256(0); /// @notice emitted when a new Token is added to the group. /// @param subToken the token added, its id will be its index in the array. event SubToken(ERC20SubToken subToken); /// @notice emitted when `owner` is allowing or disallowing `operator` to transfer tokens on its behalf. /// @param owner the address approving. /// @param operator the address being granted (or revoked) permission to transfer. /// @param approved whether the operator is granted transfer right or not. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event Minter(address minter, bool enabled); /// @notice Enable or disable the ability of `minter` to mint tokens /// @param minter address that will be given/removed minter right. /// @param enabled set whether the minter is enabled or disabled. function setMinter(address minter, bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); _setMinter(minter, enabled); } /// @notice check whether address `who` is given minter rights. /// @param who The address to query. /// @return whether the address has minter rights. function isMinter(address who) public view returns (bool) { return _minters[who]; } /// @dev mint more tokens of a specific subToken . /// @param to address receiving the tokens. /// @param id subToken id (also the index at which it was added). /// @param amount of token minted. function mint( address to, uint256 id, uint256 amount ) external { require(_minters[msg.sender], "NOT_AUTHORIZED_MINTER"); (uint256 bin, uint256 index) = id.getTokenBinIndex(); mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; toPack[bin] = toPack[bin].updateTokenBalance(index, amount, ObjectLib32.Operations.ADD); _packedSupplies[bin] = _packedSupplies[bin].updateTokenBalance(index, amount, ObjectLib32.Operations.ADD); _erc20s[id].emitTransferEvent(address(0), to, amount); } /// @dev mint more tokens of a several subToken . /// @param to address receiving the tokens. /// @param ids subToken ids (also the index at which it was added). /// @param amounts for each token minted. function batchMint( address to, uint256[] calldata ids, uint256[] calldata amounts ) external { require(_minters[msg.sender], "NOT_AUTHORIZED_MINTER"); require(ids.length == amounts.length, "INVALID_INCONSISTENT_LENGTH"); _batchMint(to, ids, amounts); } function _batchMint( address to, uint256[] memory ids, uint256[] memory amounts ) internal { uint256 lastBin = MAX_UINT256; uint256 bal = 0; uint256 supply = 0; mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; for (uint256 i = 0; i < ids.length; i++) { if (amounts[i] != 0) { (uint256 bin, uint256 index) = ids[i].getTokenBinIndex(); if (lastBin == MAX_UINT256) { lastBin = bin; bal = toPack[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); supply = _packedSupplies[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); } else { if (bin != lastBin) { toPack[lastBin] = bal; bal = toPack[bin]; _packedSupplies[lastBin] = supply; supply = _packedSupplies[bin]; lastBin = bin; } bal = bal.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); supply = supply.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.ADD); } _erc20s[ids[i]].emitTransferEvent(address(0), to, amounts[i]); } } if (lastBin != MAX_UINT256) { toPack[lastBin] = bal; _packedSupplies[lastBin] = supply; } } /// @notice return the current total supply of a specific subToken. /// @param id subToken id. /// @return supply current total number of tokens. function supplyOf(uint256 id) external view returns (uint256 supply) { (uint256 bin, uint256 index) = id.getTokenBinIndex(); return _packedSupplies[bin].getValueInBin(index); } /// @notice return the balance of a particular owner for a particular subToken. /// @param owner whose balance it is of. /// @param id subToken id. /// @return balance of the owner function balanceOf(address owner, uint256 id) public view returns (uint256 balance) { (uint256 bin, uint256 index) = id.getTokenBinIndex(); return _packedTokenBalance[owner][bin].getValueInBin(index); } /// @notice return the balances of a list of owners / subTokens. /// @param owners list of addresses to which we want to know the balance. /// @param ids list of subTokens's addresses. /// @return balances list of balances for each request. function balanceOfBatch(address[] calldata owners, uint256[] calldata ids) external view returns (uint256[] memory balances) { require(owners.length == ids.length, "INVALID_INCONSISTENT_LENGTH"); balances = new uint256[](ids.length); for (uint256 i = 0; i < ids.length; i++) { balances[i] = balanceOf(owners[i], ids[i]); } } /// @notice transfer a number of subToken from one address to another. /// @param from owner to transfer from. /// @param to destination address that will receive the tokens. /// @param id subToken id. /// @param value amount of tokens to transfer. function singleTransferFrom( address from, address to, uint256 id, uint256 value ) external { require(to != address(0), "INVALID_TO_ZERO_ADDRESS"); ERC20SubToken erc20 = _erc20s[id]; require( from == msg.sender || msg.sender == address(erc20) || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "NOT_AUTHORIZED" ); (uint256 bin, uint256 index) = id.getTokenBinIndex(); mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; fromPack[bin] = fromPack[bin].updateTokenBalance(index, value, ObjectLib32.Operations.SUB); toPack[bin] = toPack[bin].updateTokenBalance(index, value, ObjectLib32.Operations.ADD); erc20.emitTransferEvent(from, to, value); } /// @notice transfer a number of different subTokens from one address to another. /// @param from owner to transfer from. /// @param to destination address that will receive the tokens. /// @param ids list of subToken ids to transfer. /// @param values list of amount for eacg subTokens to transfer. function batchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata values ) external { require(ids.length == values.length, "INVALID_INCONSISTENT_LENGTH"); require(to != address(0), "INVALID_TO_ZERO_ADDRESS"); require( from == msg.sender || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender] || _metaTransactionContracts[msg.sender], "NOT_AUTHORIZED" ); _batchTransferFrom(from, to, ids, values); } function _batchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory values ) internal { uint256 lastBin = MAX_UINT256; uint256 balFrom; uint256 balTo; mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; mapping(uint256 => uint256) storage toPack = _packedTokenBalance[to]; for (uint256 i = 0; i < ids.length; i++) { if (values[i] != 0) { (uint256 bin, uint256 index) = ids[i].getTokenBinIndex(); if (lastBin == MAX_UINT256) { lastBin = bin; balFrom = ObjectLib32.updateTokenBalance(fromPack[bin], index, values[i], ObjectLib32.Operations.SUB); balTo = ObjectLib32.updateTokenBalance(toPack[bin], index, values[i], ObjectLib32.Operations.ADD); } else { if (bin != lastBin) { fromPack[lastBin] = balFrom; toPack[lastBin] = balTo; balFrom = fromPack[bin]; balTo = toPack[bin]; lastBin = bin; } balFrom = balFrom.updateTokenBalance(index, values[i], ObjectLib32.Operations.SUB); balTo = balTo.updateTokenBalance(index, values[i], ObjectLib32.Operations.ADD); } ERC20SubToken erc20 = _erc20s[ids[i]]; erc20.emitTransferEvent(from, to, values[i]); } } if (lastBin != MAX_UINT256) { fromPack[lastBin] = balFrom; toPack[lastBin] = balTo; } } /// @notice grant or revoke the ability for an address to transfer token on behalf of another address. /// @param sender address granting/revoking the approval. /// @param operator address being granted/revoked ability to transfer. /// @param approved whether the operator is revoked or approved. function setApprovalForAllFor( address sender, address operator, bool approved ) external { require(msg.sender == sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender], "NOT_AUTHORIZED"); _setApprovalForAll(sender, operator, approved); } /// @notice grant or revoke the ability for an address to transfer token on your behalf. /// @param operator address being granted/revoked ability to transfer. /// @param approved whether the operator is revoked or approved. function setApprovalForAll(address operator, bool approved) external { _setApprovalForAll(msg.sender, operator, approved); } /// @notice return whether an oeprator has the ability to transfer on behalf of another address. /// @param owner address who would have granted the rights. /// @param operator address being given the ability to transfer. /// @return isOperator whether the operator has approval rigths or not. function isApprovedForAll(address owner, address operator) external view returns (bool isOperator) { return _operatorsForAll[owner][operator] || _superOperators[operator]; } function isAuthorizedToTransfer(address owner, address sender) external view returns (bool) { return _metaTransactionContracts[sender] || _superOperators[sender] || _operatorsForAll[owner][sender]; } function isAuthorizedToApprove(address sender) external view returns (bool) { return _metaTransactionContracts[sender] || _superOperators[sender]; } function batchBurnFrom( address from, uint256[] calldata ids, uint256[] calldata amounts ) external { require(from != address(0), "INVALID_FROM_ZERO_ADDRESS"); require( from == msg.sender || _metaTransactionContracts[msg.sender] || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender], "NOT_AUTHORIZED" ); _batchBurnFrom(from, ids, amounts); } /// @notice burn token for a specific owner and subToken. /// @param from fron which address the token are burned from. /// @param id subToken id. /// @param value amount of tokens to burn. function burnFrom( address from, uint256 id, uint256 value ) external { require( from == msg.sender || _superOperators[msg.sender] || _operatorsForAll[from][msg.sender] || _metaTransactionContracts[msg.sender], "NOT_AUTHORIZED" ); _burn(from, id, value); } /// @notice burn token for a specific subToken. /// @param id subToken id. /// @param value amount of tokens to burn. function burn(uint256 id, uint256 value) external { _burn(msg.sender, id, value); } // ///////////////// INTERNAL ////////////////////////// function _batchBurnFrom( address from, uint256[] memory ids, uint256[] memory amounts ) internal { uint256 balFrom = 0; uint256 supply = 0; uint256 lastBin = MAX_UINT256; mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; for (uint256 i = 0; i < ids.length; i++) { if (amounts[i] != 0) { (uint256 bin, uint256 index) = ids[i].getTokenBinIndex(); if (lastBin == MAX_UINT256) { lastBin = bin; balFrom = fromPack[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); supply = _packedSupplies[bin].updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); } else { if (bin != lastBin) { fromPack[lastBin] = balFrom; balFrom = fromPack[bin]; _packedSupplies[lastBin] = supply; supply = _packedSupplies[bin]; lastBin = bin; } balFrom = balFrom.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); supply = supply.updateTokenBalance(index, amounts[i], ObjectLib32.Operations.SUB); } _erc20s[ids[i]].emitTransferEvent(from, address(0), amounts[i]); } } if (lastBin != MAX_UINT256) { fromPack[lastBin] = balFrom; _packedSupplies[lastBin] = supply; } } function _burn( address from, uint256 id, uint256 value ) internal { ERC20SubToken erc20 = _erc20s[id]; (uint256 bin, uint256 index) = id.getTokenBinIndex(); mapping(uint256 => uint256) storage fromPack = _packedTokenBalance[from]; fromPack[bin] = ObjectLib32.updateTokenBalance(fromPack[bin], index, value, ObjectLib32.Operations.SUB); _packedSupplies[bin] = ObjectLib32.updateTokenBalance(_packedSupplies[bin], index, value, ObjectLib32.Operations.SUB); erc20.emitTransferEvent(from, address(0), value); } function _addSubToken(ERC20SubToken subToken) internal returns (uint256 id) { id = _erc20s.length; require(subToken.groupAddress() == address(this), "INVALID_GROUP"); require(subToken.groupTokenId() == id, "INVALID_ID"); _erc20s.push(subToken); emit SubToken(subToken); } function _setApprovalForAll( address sender, address operator, bool approved ) internal { require(!_superOperators[operator], "INVALID_SUPER_OPERATOR"); _operatorsForAll[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } function _setMinter(address minter, bool enabled) internal { _minters[minter] = enabled; emit Minter(minter, enabled); } // ///////////////// UTILITIES ///////////////////////// using AddressUtils for address; using ObjectLib32 for ObjectLib32.Operations; using ObjectLib32 for uint256; using SafeMath for uint256; // ////////////////// DATA /////////////////////////////// mapping(uint256 => uint256) internal _packedSupplies; mapping(address => mapping(uint256 => uint256)) internal _packedTokenBalance; mapping(address => mapping(address => bool)) internal _operatorsForAll; ERC20SubToken[] internal _erc20s; mapping(address => bool) internal _minters; // ////////////// CONSTRUCTOR //////////////////////////// struct SubTokenData { string name; string symbol; } constructor( address metaTransactionContract, address admin, address initialMinter ) internal { _admin = admin; _setMetaTransactionProcessor(metaTransactionContract, true); _setMinter(initialMinter, true); } } contract CatalystDataBase is CatalystValue { event CatalystConfiguration(uint256 indexed id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee); function _setMintData(uint256 id, MintData memory data) internal { _data[id] = data; _emitConfiguration(id, data.minQuantity, data.maxQuantity, data.sandMintingFee, data.sandUpdateFee); } function _setValueOverride(uint256 id, CatalystValue valueOverride) internal { _valueOverrides[id] = valueOverride; } function _setConfiguration( uint256 id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) internal { _data[id].minQuantity = minQuantity; _data[id].maxQuantity = maxQuantity; _data[id].sandMintingFee = uint88(sandMintingFee); _data[id].sandUpdateFee = uint88(sandUpdateFee); _emitConfiguration(id, minQuantity, maxQuantity, sandMintingFee, sandUpdateFee); } function _emitConfiguration( uint256 id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) internal { emit CatalystConfiguration(id, minQuantity, maxQuantity, sandMintingFee, sandUpdateFee); } ///@dev compute a random value between min to 25. //. example: 1-25, 6-25, 11-25, 16-25 function _computeValue( uint256 seed, uint256 gemId, bytes32 blockHash, uint256 slotIndex, uint32 min ) internal pure returns (uint32) { return min + uint16(uint256(keccak256(abi.encodePacked(gemId, seed, blockHash, slotIndex))) % (26 - min)); } function getValues( uint256 catalystId, uint256 seed, GemEvent[] calldata events, uint32 totalNumberOfGemTypes ) external override view returns (uint32[] memory values) { CatalystValue valueOverride = _valueOverrides[catalystId]; if (address(valueOverride) != address(0)) { return valueOverride.getValues(catalystId, seed, events, totalNumberOfGemTypes); } values = new uint32[](totalNumberOfGemTypes); uint32 numGems; for (uint256 i = 0; i < events.length; i++) { numGems += uint32(events[i].gemIds.length); } require(numGems <= MAX_UINT32, "TOO_MANY_GEMS"); uint32 minValue = (numGems - 1) * 5 + 1; uint256 numGemsSoFar = 0; for (uint256 i = 0; i < events.length; i++) { numGemsSoFar += events[i].gemIds.length; for (uint256 j = 0; j < events[i].gemIds.length; j++) { uint256 gemId = events[i].gemIds[j]; uint256 slotIndex = numGemsSoFar - events[i].gemIds.length + j; if (values[gemId] == 0) { // first gem : value = roll between ((numGemsSoFar-1)*5+1) and 25 values[gemId] = _computeValue(seed, gemId, events[i].blockHash, slotIndex, (uint32(numGemsSoFar) - 1) * 5 + 1); // bump previous values: if (values[gemId] < minValue) { values[gemId] = minValue; } } else { // further gem, previous roll are overriden with 25 and new roll between 1 and 25 uint32 newRoll = _computeValue(seed, gemId, events[i].blockHash, slotIndex, 1); values[gemId] = (((values[gemId] - 1) / 25) + 1) * 25 + newRoll; } } } } function getMintData(uint256 catalystId) external view returns ( uint16 maxGems, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) { maxGems = _data[catalystId].maxGems; minQuantity = _data[catalystId].minQuantity; maxQuantity = _data[catalystId].maxQuantity; sandMintingFee = _data[catalystId].sandMintingFee; sandUpdateFee = _data[catalystId].sandUpdateFee; } struct MintData { uint88 sandMintingFee; uint88 sandUpdateFee; uint16 minQuantity; uint16 maxQuantity; uint16 maxGems; } uint32 internal constant MAX_UINT32 = 2**32 - 1; mapping(uint256 => MintData) internal _data; mapping(uint256 => CatalystValue) internal _valueOverrides; } contract ERC20GroupCatalyst is CatalystDataBase, ERC20Group { /// @dev add Catalyst, if one of the catalyst to be added in the batch need to have a value override, all catalyst added in that batch need to have override /// if this is not desired, they can be added in a separated batch /// if no override are needed, the valueOverrides can be left emopty function addCatalysts( ERC20SubToken[] memory catalysts, MintData[] memory mintData, CatalystValue[] memory valueOverrides ) public { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); require(catalysts.length == mintData.length, "INVALID_INCONSISTENT_LENGTH"); for (uint256 i = 0; i < mintData.length; i++) { uint256 id = _addSubToken(catalysts[i]); _setMintData(id, mintData[i]); if (valueOverrides.length > i) { _setValueOverride(id, valueOverrides[i]); } } } function addCatalyst( ERC20SubToken catalyst, MintData memory mintData, CatalystValue valueOverride ) public { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); uint256 id = _addSubToken(catalyst); _setMintData(id, mintData); _setValueOverride(id, valueOverride); } function setConfiguration( uint256 id, uint16 minQuantity, uint16 maxQuantity, uint256 sandMintingFee, uint256 sandUpdateFee ) external { // CatalystMinter hardcode the value for efficiency purpose, so a change here would require a new deployment of CatalystMinter require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); _setConfiguration(id, minQuantity, maxQuantity, sandMintingFee, sandUpdateFee); } constructor( address metaTransactionContract, address admin, address initialMinter ) public ERC20Group(metaTransactionContract, admin, initialMinter) {} } contract ERC20GroupGem is ERC20Group { function addGems(ERC20SubToken[] calldata catalysts) external { require(msg.sender == _admin, "NOT_AUTHORIZED_ADMIN"); for (uint256 i = 0; i < catalysts.length; i++) { _addSubToken(catalysts[i]); } } constructor( address metaTransactionContract, address admin, address initialMinter ) public ERC20Group(metaTransactionContract, admin, initialMinter) {} } contract PurchaseValidator is Admin { address private _signingWallet; // A parallel-queue mapping to nonces. mapping(address => mapping(uint128 => uint128)) public queuedNonces; /// @notice Function to get the nonce for a given address and queue ID /// @param _buyer The address of the starterPack purchaser /// @param _queueId The ID of the nonce queue for the given address. /// The default is queueID=0, and the max is queueID=2**128-1 /// @return uint128 representing the requestied nonce function getNonceByBuyer(address _buyer, uint128 _queueId) external view returns (uint128) { return queuedNonces[_buyer][_queueId]; } /// @notice Check if a purchase message is valid /// @param buyer The address paying for the purchase & receiving tokens /// @param catalystIds The catalyst IDs to be purchased /// @param catalystQuantities The quantities of the catalysts to be purchased /// @param gemIds The gem IDs to be purchased /// @param gemQuantities The quantities of the gems to be purchased /// @param nonce The current nonce for the user. This is represented as a /// uint256 value, but is actually 2 packed uint128's (queueId + nonce) /// @param signature A signed message specifying tx details /// @return True if the purchase is valid function isPurchaseValid( address buyer, uint256[] memory catalystIds, uint256[] memory catalystQuantities, uint256[] memory gemIds, uint256[] memory gemQuantities, uint256 nonce, bytes memory signature ) public returns (bool) { require(_checkAndUpdateNonce(buyer, nonce), "INVALID_NONCE"); bytes32 hashedData = keccak256(abi.encodePacked(catalystIds, catalystQuantities, gemIds, gemQuantities, buyer, nonce)); address signer = SigUtil.recover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashedData)), signature); return signer == _signingWallet; } /// @notice Get the wallet authorized for signing purchase-messages. /// @return the address of the signing wallet function getSigningWallet() external view returns (address) { return _signingWallet; } /// @notice Update the signing wallet address /// @param newSigningWallet The new address of the signing wallet function updateSigningWallet(address newSigningWallet) external { require(_admin == msg.sender, "SENDER_NOT_ADMIN"); _signingWallet = newSigningWallet; } /// @dev Function for validating the nonce for a user. /// @param _buyer The address for which we want to check the nonce /// @param _packedValue The queueId + nonce, packed together. /// EG: for queueId=42 nonce=7, pass: "0x0000000000000000000000000000002A00000000000000000000000000000007" function _checkAndUpdateNonce(address _buyer, uint256 _packedValue) private returns (bool) { uint128 queueId = uint128(_packedValue / 2**128); uint128 nonce = uint128(_packedValue % 2**128); uint128 currentNonce = queuedNonces[_buyer][queueId]; if (nonce == currentNonce) { queuedNonces[_buyer][queueId] = currentNonce + 1; return true; } return false; } constructor(address initialSigningWallet) public { _signingWallet = initialSigningWallet; } } contract StarterPackV1 is Admin, MetaTransactionReceiver, PurchaseValidator { using SafeMathWithRequire for uint256; uint256 internal constant DAI_PRICE = 44000000000000000; uint256 private constant DECIMAL_PLACES = 1 ether; ERC20 internal immutable _sand; Medianizer private immutable _medianizer; ERC20 private immutable _dai; ERC20Group internal immutable _erc20GroupCatalyst; ERC20Group internal immutable _erc20GroupGem; bool _sandEnabled; bool _etherEnabled; bool _daiEnabled; uint256[] private _starterPackPrices; uint256[] private _previousStarterPackPrices; uint256 private _gemPrice; uint256 private _previousGemPrice; // The timestamp of the last pricechange uint256 private _priceChangeTimestamp; address payable internal _wallet; // The delay between calling setPrices() and when the new prices come into effect. // Minimizes the effect of price changes on pending TXs uint256 private constant PRICE_CHANGE_DELAY = 1 hours; event Purchase(address indexed buyer, Message message, uint256 price, address token, uint256 amountPaid); event SetPrices(uint256[] prices, uint256 gemPrice); struct Message { uint256[] catalystIds; uint256[] catalystQuantities; uint256[] gemIds; uint256[] gemQuantities; uint256 nonce; } // ////////////////////////// Functions //////////////////////// /// @notice Set the wallet receiving the proceeds /// @param newWallet Address of the new receiving wallet function setReceivingWallet(address payable newWallet) external { require(newWallet != address(0), "WALLET_ZERO_ADDRESS"); require(msg.sender == _admin, "NOT_AUTHORIZED"); _wallet = newWallet; } /// @notice Enable / disable DAI payment for StarterPacks /// @param enabled Whether to enable or disable function setDAIEnabled(bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _daiEnabled = enabled; } /// @notice Return whether DAI payments are enabled /// @return Whether DAI payments are enabled function isDAIEnabled() external view returns (bool) { return _daiEnabled; } /// @notice Enable / disable ETH payment for StarterPacks /// @param enabled Whether to enable or disable function setETHEnabled(bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _etherEnabled = enabled; } /// @notice Return whether ETH payments are enabled /// @return Whether ETH payments are enabled function isETHEnabled() external view returns (bool) { return _etherEnabled; } /// @dev Enable / disable the specific SAND payment for StarterPacks /// @param enabled Whether to enable or disable function setSANDEnabled(bool enabled) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _sandEnabled = enabled; } /// @notice Return whether SAND payments are enabled /// @return Whether SAND payments are enabled function isSANDEnabled() external view returns (bool) { return _sandEnabled; } /// @notice Purchase StarterPacks with SAND /// @param buyer The destination address for the purchased Catalysts and Gems and the address that will pay for the purchase; if not metaTx then buyer must be equal to msg.sender /// @param message A message containing information about the Catalysts and Gems to be purchased /// @param signature A signed message specifying tx details function purchaseWithSand( address buyer, Message calldata message, bytes calldata signature ) external { require(msg.sender == buyer || _metaTransactionContracts[msg.sender], "INVALID_SENDER"); require(_sandEnabled, "SAND_IS_NOT_ENABLED"); require(buyer != address(0), "DESTINATION_ZERO_ADDRESS"); require( isPurchaseValid(buyer, message.catalystIds, message.catalystQuantities, message.gemIds, message.gemQuantities, message.nonce, signature), "INVALID_PURCHASE" ); uint256 amountInSand = _calculateTotalPriceInSand(message.catalystIds, message.catalystQuantities, message.gemQuantities); _handlePurchaseWithERC20(buyer, _wallet, address(_sand), amountInSand); _erc20GroupCatalyst.batchTransferFrom(address(this), buyer, message.catalystIds, message.catalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), buyer, message.gemIds, message.gemQuantities); emit Purchase(buyer, message, amountInSand, address(_sand), amountInSand); } /// @notice Purchase StarterPacks with Ether /// @param buyer The destination address for the purchased Catalysts and Gems and the address that will pay for the purchase; if not metaTx then buyer must be equal to msg.sender /// @param message A message containing information about the Catalysts and Gems to be purchased /// @param signature A signed message specifying tx details function purchaseWithETH( address buyer, Message calldata message, bytes calldata signature ) external payable { require(msg.sender == buyer || _metaTransactionContracts[msg.sender], "INVALID_SENDER"); require(_etherEnabled, "ETHER_IS_NOT_ENABLED"); require(buyer != address(0), "DESTINATION_ZERO_ADDRESS"); require(buyer != address(this), "DESTINATION_STARTERPACKV1_CONTRACT"); require( isPurchaseValid(buyer, message.catalystIds, message.catalystQuantities, message.gemIds, message.gemQuantities, message.nonce, signature), "INVALID_PURCHASE" ); uint256 amountInSand = _calculateTotalPriceInSand(message.catalystIds, message.catalystQuantities, message.gemQuantities); uint256 ETHRequired = getEtherAmountWithSAND(amountInSand); require(msg.value >= ETHRequired, "NOT_ENOUGH_ETHER_SENT"); _wallet.transfer(ETHRequired); _erc20GroupCatalyst.batchTransferFrom(address(this), buyer, message.catalystIds, message.catalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), buyer, message.gemIds, message.gemQuantities); emit Purchase(buyer, message, amountInSand, address(0), ETHRequired); if (msg.value - ETHRequired > 0) { // refund extra (bool success, ) = msg.sender.call{value: msg.value - ETHRequired}(""); require(success, "REFUND_FAILED"); } } /// @notice Purchase StarterPacks with DAI /// @param buyer The destination address for the purchased Catalysts and Gems and the address that will pay for the purchase; if not metaTx then buyer must be equal to msg.sender /// @param message A message containing information about the Catalysts and Gems to be purchased /// @param signature A signed message specifying tx details function purchaseWithDAI( address buyer, Message calldata message, bytes calldata signature ) external { require(msg.sender == buyer || _metaTransactionContracts[msg.sender], "INVALID_SENDER"); require(_daiEnabled, "DAI_IS_NOT_ENABLED"); require(buyer != address(0), "DESTINATION_ZERO_ADDRESS"); require(buyer != address(this), "DESTINATION_STARTERPACKV1_CONTRACT"); require( isPurchaseValid(buyer, message.catalystIds, message.catalystQuantities, message.gemIds, message.gemQuantities, message.nonce, signature), "INVALID_PURCHASE" ); uint256 amountInSand = _calculateTotalPriceInSand(message.catalystIds, message.catalystQuantities, message.gemQuantities); uint256 DAIRequired = amountInSand.mul(DAI_PRICE).div(DECIMAL_PLACES); _handlePurchaseWithERC20(buyer, _wallet, address(_dai), DAIRequired); _erc20GroupCatalyst.batchTransferFrom(address(this), buyer, message.catalystIds, message.catalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), buyer, message.gemIds, message.gemQuantities); emit Purchase(buyer, message, amountInSand, address(_dai), DAIRequired); } /// @notice Enables admin to withdraw all remaining tokens /// @param to The destination address for the purchased Catalysts and Gems /// @param catalystIds The IDs of the catalysts to be transferred /// @param gemIds The IDs of the gems to be transferred function withdrawAll( address to, uint256[] calldata catalystIds, uint256[] calldata gemIds ) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); address[] memory catalystAddresses = new address[](catalystIds.length); for (uint256 i = 0; i < catalystIds.length; i++) { catalystAddresses[i] = address(this); } address[] memory gemAddresses = new address[](gemIds.length); for (uint256 i = 0; i < gemIds.length; i++) { gemAddresses[i] = address(this); } uint256[] memory unsoldCatalystQuantities = _erc20GroupCatalyst.balanceOfBatch(catalystAddresses, catalystIds); uint256[] memory unsoldGemQuantities = _erc20GroupGem.balanceOfBatch(gemAddresses, gemIds); _erc20GroupCatalyst.batchTransferFrom(address(this), to, catalystIds, unsoldCatalystQuantities); _erc20GroupGem.batchTransferFrom(address(this), to, gemIds, unsoldGemQuantities); } /// @notice Enables admin to change the prices of the StarterPack bundles /// @param prices Array of new prices that will take effect after a delay period /// @param gemPrice New price for gems that will take effect after a delay period function setPrices(uint256[] calldata prices, uint256 gemPrice) external { require(msg.sender == _admin, "NOT_AUTHORIZED"); _previousStarterPackPrices = _starterPackPrices; _starterPackPrices = prices; _previousGemPrice = _gemPrice; _gemPrice = gemPrice; _priceChangeTimestamp = now; emit SetPrices(prices, gemPrice); } /// @notice Get current StarterPack prices /// @return pricesBeforeSwitch Array of prices before price change /// @return pricesAfterSwitch Array of prices after price change /// @return gemPriceBeforeSwitch Gem price before price change /// @return gemPriceAfterSwitch Gem price after price change /// @return switchTime The time the latest price change will take effect, being the time of the price change plus the price change delay function getPrices() external view returns ( uint256[] memory pricesBeforeSwitch, uint256[] memory pricesAfterSwitch, uint256 gemPriceBeforeSwitch, uint256 gemPriceAfterSwitch, uint256 switchTime ) { switchTime = 0; if (_priceChangeTimestamp != 0) { switchTime = _priceChangeTimestamp + PRICE_CHANGE_DELAY; } return (_previousStarterPackPrices, _starterPackPrices, _previousGemPrice, _gemPrice, switchTime); } /// @notice Returns the amount of ETH for a specific amount of SAND /// @param sandAmount An amount of SAND /// @return The amount of ETH function getEtherAmountWithSAND(uint256 sandAmount) public view returns (uint256) { uint256 ethUsdPair = _getEthUsdPair(); return sandAmount.mul(DAI_PRICE).div(ethUsdPair); } // ////////////////////////// Internal //////////////////////// /// @dev Gets the ETHUSD pair from the Medianizer contract /// @return The pair as an uint256 function _getEthUsdPair() internal view returns (uint256) { bytes32 pair = _medianizer.read(); return uint256(pair); } /// @dev Function to calculate the total price in SAND of the StarterPacks to be purchased /// @dev The price of each StarterPack relates to the catalystId /// @param catalystIds Array of catalystIds to be purchase /// @param catalystQuantities Array of quantities of those catalystIds to be purchased /// @return Total price in SAND function _calculateTotalPriceInSand( uint256[] memory catalystIds, uint256[] memory catalystQuantities, uint256[] memory gemQuantities ) internal returns (uint256) { require(catalystIds.length == catalystQuantities.length, "INVALID_INPUT"); (uint256[] memory prices, uint256 gemPrice) = _priceSelector(); uint256 totalPrice; for (uint256 i = 0; i < catalystIds.length; i++) { uint256 id = catalystIds[i]; uint256 quantity = catalystQuantities[i]; totalPrice = totalPrice.add(prices[id].mul(quantity)); } for (uint256 i = 0; i < gemQuantities.length; i++) { uint256 quantity = gemQuantities[i]; totalPrice = totalPrice.add(gemPrice.mul(quantity)); } return totalPrice; } /// @dev Function to determine whether to use old or new prices /// @return Array of prices function _priceSelector() internal returns (uint256[] memory, uint256) { uint256[] memory prices; uint256 gemPrice; // No price change: if (_priceChangeTimestamp == 0) { prices = _starterPackPrices; gemPrice = _gemPrice; } else { // Price change delay has expired. if (now > _priceChangeTimestamp + PRICE_CHANGE_DELAY) { _priceChangeTimestamp = 0; prices = _starterPackPrices; gemPrice = _gemPrice; } else { // Price change has occured: prices = _previousStarterPackPrices; gemPrice = _previousGemPrice; } } return (prices, gemPrice); } /// @dev Function to handle purchase with SAND or DAI function _handlePurchaseWithERC20( address buyer, address payable paymentRecipient, address tokenAddress, uint256 amount ) internal { ERC20 token = ERC20(tokenAddress); uint256 amountForDestination = amount; require(token.transferFrom(buyer, paymentRecipient, amountForDestination), "PAYMENT_TRANSFER_FAILED"); } // /////////////////// CONSTRUCTOR //////////////////// constructor( address starterPackAdmin, address sandContractAddress, address initialMetaTx, address payable initialWalletAddress, address medianizerContractAddress, address daiTokenContractAddress, address erc20GroupCatalystAddress, address erc20GroupGemAddress, address initialSigningWallet, uint256[] memory initialStarterPackPrices, uint256 initialGemPrice ) public PurchaseValidator(initialSigningWallet) { _setMetaTransactionProcessor(initialMetaTx, true); _wallet = initialWalletAddress; _admin = starterPackAdmin; _sand = ERC20(sandContractAddress); _medianizer = Medianizer(medianizerContractAddress); _dai = ERC20(daiTokenContractAddress); _erc20GroupCatalyst = ERC20Group(erc20GroupCatalystAddress); _erc20GroupGem = ERC20Group(erc20GroupGemAddress); _starterPackPrices = initialStarterPackPrices; _previousStarterPackPrices = initialStarterPackPrices; _gemPrice = initialGemPrice; _previousGemPrice = initialGemPrice; _sandEnabled = true; // Sand is enabled by default _etherEnabled = true; // Ether is enabled by default } }
0x6080604052600436106101805760003560e01c80638f283970116100d6578063bf5c3e9f1161007f578063d1b8f6b311610059578063d1b8f6b314610406578063dc5074af14610426578063e97eb0a21461044657610180565b8063bf5c3e9f146103b1578063c96f8902146103d1578063caed3500146103f157610180565b8063b0e6bfaa116100b0578063b0e6bfaa1461034b578063b522ecff1461036b578063bd9a548b1461038b57610180565b80638f283970146102f6578063915c851314610316578063a7e306841461033657610180565b806358bc2944116101385780636e9960c3116101125780636e9960c3146102945780637c53ec4c146102b65780638a04af6a146102d657610180565b806358bc2944146102345780635d8e3021146102545780635f995c2d1461028157610180565b8063427b8d3411610169578063427b8d34146101c75780634a253778146101f25780634d08cbc11461020757610180565b80633b7c4c15146101855780633d5f167b146101a7575b600080fd5b34801561019157600080fd5b506101a56101a0366004612497565b610466565b005b3480156101b357600080fd5b506101a56101c23660046123ba565b6104d1565b3480156101d357600080fd5b506101dc610568565b6040516101e991906128b1565b60405180910390f35b3480156101fe57600080fd5b506101dc610578565b34801561021357600080fd5b50610227610222366004612379565b610586565b6040516101e99190612d73565b34801561024057600080fd5b506101a561024f366004612118565b6105c5565b34801561026057600080fd5b5061027461026f3660046124e7565b61061e565b6040516101e99190612d90565b6101a561028f3660046122d3565b610659565b3480156102a057600080fd5b506102a9610bab565b6040516101e991906126e3565b3480156102c257600080fd5b506101a56102d1366004612497565b610bba565b3480156102e257600080fd5b506101a56102f136600461229b565b610bf7565b34801561030257600080fd5b506101a5610311366004612118565b610c2f565b34801561032257600080fd5b506101dc6103313660046121b4565b610ccf565b34801561034257600080fd5b506101dc610d7d565b34801561035757600080fd5b506101a56103663660046122d3565b610d86565b34801561037757600080fd5b506101a5610386366004612118565b611085565b34801561039757600080fd5b506103a0611104565b6040516101e995949392919061286e565b3480156103bd57600080fd5b506102276103cc366004612379565b6111e2565b3480156103dd57600080fd5b506101a56103ec366004612134565b611211565b3480156103fd57600080fd5b506102a96115ed565b34801561041257600080fd5b506101a56104213660046122d3565b6115fc565b34801561043257600080fd5b506101dc610441366004612118565b6118a4565b34801561045257600080fd5b506101a5610461366004612497565b6118c2565b6000546001600160a01b031633146104995760405162461bcd60e51b815260040161049090612c70565b60405180910390fd5b6004805491151562010000027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ffff909216919091179055565b6000546001600160a01b031633146104fb5760405162461bcd60e51b815260040161049090612c70565b6005805461050b91600691611f48565b5061051860058484611f98565b5060078054600855819055426009556040517fb4484e658d3a3ea551621c62bec48be6ac3aab4615fa987434fa1bd62bd76c939061055b9085908590859061284a565b60405180910390a1505050565b60045462010000900460ff165b90565b600454610100900460ff1690565b6001600160a01b03821660009081526003602090815260408083206fffffffffffffffffffffffffffffffff8086168552925290912054165b92915050565b6000546001600160a01b031633146105ef5760405162461bcd60e51b815260040161049090612b37565b6002805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b600080610629611923565b90506106528161064685669c51c4521e000063ffffffff6119bd16565b9063ffffffff6119f816565b9392505050565b336001600160a01b038516148061067f57503360009081526001602052604090205460ff165b61069b5760405162461bcd60e51b815260040161049090612bcb565b600454610100900460ff166106c25760405162461bcd60e51b8152600401610490906129ed565b6001600160a01b0384166106e85760405162461bcd60e51b815260040161049090612911565b6001600160a01b0384163014156107115760405162461bcd60e51b815260040161049090612ca7565b61084d8461071f8580612d99565b8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525061075e925050506020870187612d99565b8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525061079d925050506040880188612d99565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506107dc925050506060890189612d99565b8080602002602001604051908101604052809392919081815260200183836020028082843760009201919091525050604080516020601f8c018190048102820181019092528a815260808d0135935091508a908a9081908401838280828437600092019190915250610ccf92505050565b6108695760405162461bcd60e51b815260040161049090612a92565b600061092d6108788580612d99565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506108b7925050506020870187612d99565b808060200260200160405190810160405280939291908181526020018383602002808284376000920191909152506108f6925050506060880188612d99565b80806020026020016040519081016040528093929190818152602001838360200280828437600092019190915250611a2892505050565b9050600061093a8261061e565b90508034101561095c5760405162461bcd60e51b815260040161049090612948565b600a546040516001600160a01b039091169082156108fc029083906000818181858888f19350505050158015610996573d6000803e3d6000fd5b506001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f1166317fad7fc30886109d28980612d99565b6109df60208c018c612d99565b6040518763ffffffff1660e01b8152600401610a0096959493929190612735565b600060405180830381600087803b158015610a1a57600080fd5b505af1158015610a2e573d6000803e3d6000fd5b50506001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51691506317fad7fc90503088610a7260408a018a612d99565b610a7f60608c018c612d99565b6040518763ffffffff1660e01b8152600401610aa096959493929190612735565b600060405180830381600087803b158015610aba57600080fd5b505af1158015610ace573d6000803e3d6000fd5b50505050856001600160a01b03167fdfdb2e8aa552e0517bf744153975973b0beb2bedf0e81bbf58d7744b738197b88684600085604051610b129493929190612d3b565b60405180910390a23481900315610ba3576000336001600160a01b0316823403604051610b3e90610575565b60006040518083038185875af1925050503d8060008114610b7b576040519150601f19603f3d011682016040523d82523d6000602084013e610b80565b606091505b5050905080610ba15760405162461bcd60e51b815260040161049090612ac9565b505b505050505050565b6000546001600160a01b031690565b6000546001600160a01b03163314610be45760405162461bcd60e51b815260040161049090612c70565b6004805460ff1916911515919091179055565b6000546001600160a01b03163314610c215760405162461bcd60e51b815260040161049090612b6e565b610c2b8282611b39565b5050565b6000546001600160a01b03163314610c595760405162461bcd60e51b815260040161049090612c02565b6000546040517f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f91610c98916001600160a01b039091169084906126f7565b60405180910390a16000805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b6000610cdb8884611b9b565b610cf75760405162461bcd60e51b815260040161049090612b00565b6000878787878c88604051602001610d149695949392919061264f565b6040516020818303038152906040528051906020012090506000610d5e82604051602001610d4291906126b2565b6040516020818303038152906040528051906020012085611c72565b6002546001600160a01b039081169116149a9950505050505050505050565b60045460ff1690565b336001600160a01b0385161480610dac57503360009081526001602052604090205460ff165b610dc85760405162461bcd60e51b815260040161049090612bcb565b60045462010000900460ff16610df05760405162461bcd60e51b8152600401610490906128da565b6001600160a01b038416610e165760405162461bcd60e51b815260040161049090612911565b6001600160a01b038416301415610e3f5760405162461bcd60e51b815260040161049090612ca7565b610e4d8461071f8580612d99565b610e695760405162461bcd60e51b815260040161049090612a92565b6000610e786108788580612d99565b90506000610e9f670de0b6b3a764000061064684669c51c4521e000063ffffffff6119bd16565b600a54909150610edb9087906001600160a01b03167f0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f84611d2d565b6001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f1166317fad7fc3088610f168980612d99565b610f2360208c018c612d99565b6040518763ffffffff1660e01b8152600401610f4496959493929190612735565b600060405180830381600087803b158015610f5e57600080fd5b505af1158015610f72573d6000803e3d6000fd5b50506001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51691506317fad7fc90503088610fb660408a018a612d99565b610fc360608c018c612d99565b6040518763ffffffff1660e01b8152600401610fe496959493929190612735565b600060405180830381600087803b158015610ffe57600080fd5b505af1158015611012573d6000803e3d6000fd5b50505050856001600160a01b03167fdfdb2e8aa552e0517bf744153975973b0beb2bedf0e81bbf58d7744b738197b886847f0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f856040516110759493929190612d3b565b60405180910390a2505050505050565b6001600160a01b0381166110ab5760405162461bcd60e51b815260040161049090612a5b565b6000546001600160a01b031633146110d55760405162461bcd60e51b815260040161049090612c70565b600a805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60608060008060008090506009546000146111225750600954610e10015b60066005600854600754848480548060200260200160405190810160405280929190818152602001828054801561117857602002820191906000526020600020905b815481526020019060010190808311611164575b50505050509450838054806020026020016040519081016040528092919081815260200182805480156111ca57602002820191906000526020600020905b8154815260200190600101908083116111b6575b50505050509350945094509450945094509091929394565b60036020908152600092835260408084209091529082529020546fffffffffffffffffffffffffffffffff1681565b6000546001600160a01b0316331461123b5760405162461bcd60e51b815260040161049090612c70565b60608367ffffffffffffffff8111801561125457600080fd5b5060405190808252806020026020018201604052801561127e578160200160208202803683370190505b50905060005b848110156112b9573082828151811061129957fe5b6001600160a01b0390921660209283029190910190910152600101611284565b5060608267ffffffffffffffff811180156112d357600080fd5b506040519080825280602002602001820160405280156112fd578160200160208202803683370190505b50905060005b83811015611338573082828151811061131857fe5b6001600160a01b0390921660209283029190910190910152600101611303565b506040517f4e1273f40000000000000000000000000000000000000000000000000000000081526060906001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f11690634e1273f4906113a59086908b908b906004016127e8565b60006040518083038186803b1580156113bd57600080fd5b505afa1580156113d1573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526113f99190810190612404565b905060607f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba56001600160a01b0316634e1273f48488886040518463ffffffff1660e01b815260040161144d939291906127e8565b60006040518083038186803b15801561146557600080fd5b505afa158015611479573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526114a19190810190612404565b6040517f17fad7fc0000000000000000000000000000000000000000000000000000000081529091506001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f116906317fad7fc906115119030908d908d908d908990600401612782565b600060405180830381600087803b15801561152b57600080fd5b505af115801561153f573d6000803e3d6000fd5b50506040517f17fad7fc0000000000000000000000000000000000000000000000000000000081526001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51692506317fad7fc91506115b09030908d908b908b908890600401612782565b600060405180830381600087803b1580156115ca57600080fd5b505af11580156115de573d6000803e3d6000fd5b50505050505050505050505050565b6002546001600160a01b031690565b336001600160a01b038516148061162257503360009081526001602052604090205460ff165b61163e5760405162461bcd60e51b815260040161049090612bcb565b60045460ff166116605760405162461bcd60e51b8152600401610490906129b6565b6001600160a01b0384166116865760405162461bcd60e51b815260040161049090612911565b6116948461071f8580612d99565b6116b05760405162461bcd60e51b815260040161049090612a92565b60006116bf6108788580612d99565b600a549091506116fb9086906001600160a01b03167f0000000000000000000000003845badade8e6dff049820680d1f14bd3903a5d084611d2d565b6001600160a01b037f0000000000000000000000002fc246149b4b8d7bcef6188a10af1791380227f1166317fad7fc30876117368880612d99565b61174360208b018b612d99565b6040518763ffffffff1660e01b815260040161176496959493929190612735565b600060405180830381600087803b15801561177e57600080fd5b505af1158015611792573d6000803e3d6000fd5b50506001600160a01b037f0000000000000000000000008ff2611da386de427fc96a8073963619c5851ba51691506317fad7fc905030876117d66040890189612d99565b6117e360608b018b612d99565b6040518763ffffffff1660e01b815260040161180496959493929190612735565b600060405180830381600087803b15801561181e57600080fd5b505af1158015611832573d6000803e3d6000fd5b50505050846001600160a01b03167fdfdb2e8aa552e0517bf744153975973b0beb2bedf0e81bbf58d7744b738197b885837f0000000000000000000000003845badade8e6dff049820680d1f14bd3903a5d0856040516118959493929190612d3b565b60405180910390a25050505050565b6001600160a01b031660009081526001602052604090205460ff1690565b6000546001600160a01b031633146118ec5760405162461bcd60e51b815260040161049090612c70565b60048054911515610100027fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00ff909216919091179055565b6000807f000000000000000000000000729d19f657bd0614b4985cf1d82531c67569197b6001600160a01b03166357de26a46040518163ffffffff1660e01b815260040160206040518083038186803b15801561197f57600080fd5b505afa158015611993573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119b791906124cf565b91505090565b6000826119cc575060006105bf565b50818102818382816119da57fe5b04146105bf5760405162461bcd60e51b815260040161049090612c39565b600081611a175760405162461bcd60e51b815260040161049090612d04565b818381611a2057fe5b049392505050565b60008251845114611a4b5760405162461bcd60e51b815260040161049090612a24565b60606000611a57611de8565b90925090506000805b8751811015611adb576000888281518110611a7757fe5b602002602001015190506000888381518110611a8f57fe5b60200260200101519050611acf611ac282888581518110611aac57fe5b60200260200101516119bd90919063ffffffff16565b859063ffffffff611f2516565b93505050600101611a60565b5060005b8551811015611b2e576000868281518110611af657fe5b60200260200101519050611b23611b1682866119bd90919063ffffffff16565b849063ffffffff611f2516565b925050600101611adf565b509695505050505050565b6001600160a01b03821660009081526001602052604090819020805460ff1916831515179055517fb21eb88b4e33b3f1281830a7178d74d8aa73220416215726b68ae23d539515cb90611b8f90849084906127cd565b60405180910390a15050565b6001600160a01b038216600090815260036020908152604080832070010000000000000000000000000000000085046fffffffffffffffffffffffffffffffff81811686529190935290832054848216911680821415611c66576001600160a01b03861660009081526003602090815260408083206fffffffffffffffffffffffffffffffff9687168452909152902080547fffffffffffffffffffffffffffffffff00000000000000000000000000000000166001928301909416939093179092555090506105bf565b50600095945050505050565b60008151604114611c8257600080fd5b60208201516040830151606084015160001a601b811015611ca157601b015b8060ff16601b1480611cb657508060ff16601c145b611cbf57600080fd5b60018682858560405160008152602001604052604051611ce294939291906128bc565b6020604051602081039080840390855afa158015611d04573d6000803e3d6000fd5b5050604051601f1901519450506001600160a01b038416611d2457600080fd5b50505092915050565b6040517f23b872dd000000000000000000000000000000000000000000000000000000008152829082906001600160a01b038316906323b872dd90611d7a90899089908690600401612711565b602060405180830381600087803b158015611d9457600080fd5b505af1158015611da8573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dcc91906124b3565b610ba35760405162461bcd60e51b81526004016104909061297f565b606060006060600060095460001415611e58576005805480602002602001604051908101604052809291908181526020018280548015611e4757602002820191906000526020600020905b815481526020019060010190808311611e33575b505050505091506007549050611f1c565b610e1060095401421115611ec35760006009556005805460408051602080840282018101909252828152929190830182828015611e475760200282019190600052602060002090815481526020019060010190808311611e3357505050505091506007549050611f1c565b6006805480602002602001604051908101604052809291908181526020018280548015611f0f57602002820191906000526020600020905b815481526020019060010190808311611efb575b5050505050915060085490505b90925090509091565b818101828110156105bf5760405162461bcd60e51b815260040161049090612c39565b828054828255906000526020600020908101928215611f885760005260206000209182015b82811115611f88578254825591600101919060010190611f6d565b50611f94929150611fd3565b5090565b828054828255906000526020600020908101928215611f88579160200282015b82811115611f88578235825591602001919060010190611fb8565b61057591905b80821115611f945760008155600101611fd9565b80356105bf81612e73565b60008083601f840112612009578182fd5b50813567ffffffffffffffff811115612020578182fd5b602083019150836020808302850101111561203a57600080fd5b9250929050565b600082601f830112612051578081fd5b813561206461205f82612e0b565b612de4565b81815291506020808301908481018184028601820187101561208557600080fd5b60005b848110156120a457813584529282019290820190600101612088565b505050505092915050565b600082601f8301126120bf578081fd5b813567ffffffffffffffff8111156120d5578182fd5b6120e86020601f19601f84011601612de4565b91508082528360208285010111156120ff57600080fd5b8060208401602084013760009082016020015292915050565b600060208284031215612129578081fd5b813561065281612e73565b60008060008060006060868803121561214b578081fd5b853561215681612e73565b9450602086013567ffffffffffffffff80821115612172578283fd5b61217e89838a01611ff8565b90965094506040880135915080821115612196578283fd5b506121a388828901611ff8565b969995985093965092949392505050565b600080600080600080600060e0888a0312156121ce578182fd5b6121d88989611fed565b9650602088013567ffffffffffffffff808211156121f4578384fd5b6122008b838c01612041565b975060408a0135915080821115612215578384fd5b6122218b838c01612041565b965060608a0135915080821115612236578384fd5b6122428b838c01612041565b955060808a0135915080821115612257578384fd5b6122638b838c01612041565b945060a08a0135935060c08a013591508082111561227f578283fd5b5061228c8a828b016120af565b91505092959891949750929550565b600080604083850312156122ad578182fd5b82356122b881612e73565b915060208301356122c881612e8b565b809150509250929050565b600080600080606085870312156122e8578384fd5b84356122f381612e73565b9350602085013567ffffffffffffffff8082111561230f578485fd5b81870160a0818a031215612321578586fd5b94506040870135915080821115612336578384fd5b81870188601f820112612347578485fd5b8035925081831115612357578485fd5b886020848301011115612368578485fd5b959894975050602090940194505050565b6000806040838503121561238b578182fd5b823561239681612e73565b915060208301356fffffffffffffffffffffffffffffffff811681146122c8578182fd5b6000806000604084860312156123ce578283fd5b833567ffffffffffffffff8111156123e4578384fd5b6123f086828701611ff8565b909790965060209590950135949350505050565b60006020808385031215612416578182fd5b825167ffffffffffffffff81111561242c578283fd5b80840185601f82011261243d578384fd5b8051915061244d61205f83612e0b565b8281528381019082850185850284018601891015612469578687fd5b8693505b8484101561248b57805183526001939093019291850191850161246d565b50979650505050505050565b6000602082840312156124a8578081fd5b813561065281612e8b565b6000602082840312156124c4578081fd5b815161065281612e8b565b6000602082840312156124e0578081fd5b5051919050565b6000602082840312156124f8578081fd5b5035919050565b60008284527f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff831115612530578081fd5b6020830280836020870137939093016020019283525090919050565b6000815180845260208085019450808401835b8381101561257b5781518752958201959082019060010161255f565b509495945050505050565b8051600090602080840183831561257b5781518752958201959082019060010161255f565b60006125b78283612e2b565b60a085526125c960a0860182846124ff565b6125d66020860186612e2b565b9350915085810360208701526125ed8184846124ff565b6125fa6040870187612e2b565b9450925086810360408801526126118185856124ff565b9150506126216060860186612e2b565b9350915085810360608701526126388184846124ff565b608086013560808801528094505050505092915050565b600061267661267061266a612664858c612586565b8a612586565b88612586565b86612586565b60609490941b7fffffffffffffffffffffffffffffffffffffffff00000000000000000000000016845250506014820152603401949350505050565b7f19457468657265756d205369676e6564204d6573736167653a0a3332000000008152601c810191909152603c0190565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60006001600160a01b038089168352808816602084015250608060408301526127626080830186886124ff565b82810360608401526127758185876124ff565b9998505050505050505050565b60006001600160a01b038088168352808716602084015250608060408301526127af6080830185876124ff565b82810360608401526127c1818561254c565b98975050505050505050565b6001600160a01b039290921682521515602082015260400190565b604080825284519082018190526000906020906060840190828801845b8281101561282a5781516001600160a01b031684529284019290840190600101612805565b5050508381038285015261283f8186886124ff565b979650505050505050565b60006040825261285e6040830185876124ff565b9050826020830152949350505050565b600060a0825261288160a083018861254c565b8281036020840152612893818861254c565b60408401969096525050606081019290925260809091015292915050565b901515815260200190565b93845260ff9290921660208401526040830152606082015260800190565b60208082526012908201527f4441495f49535f4e4f545f454e41424c45440000000000000000000000000000604082015260600190565b60208082526018908201527f44455354494e4154494f4e5f5a45524f5f414444524553530000000000000000604082015260600190565b60208082526015908201527f4e4f545f454e4f5547485f45544845525f53454e540000000000000000000000604082015260600190565b60208082526017908201527f5041594d454e545f5452414e534645525f4641494c4544000000000000000000604082015260600190565b60208082526013908201527f53414e445f49535f4e4f545f454e41424c454400000000000000000000000000604082015260600190565b60208082526014908201527f45544845525f49535f4e4f545f454e41424c4544000000000000000000000000604082015260600190565b6020808252600d908201527f494e56414c49445f494e50555400000000000000000000000000000000000000604082015260600190565b60208082526013908201527f57414c4c45545f5a45524f5f4144445245535300000000000000000000000000604082015260600190565b60208082526010908201527f494e56414c49445f505552434841534500000000000000000000000000000000604082015260600190565b6020808252600d908201527f524546554e445f4641494c454400000000000000000000000000000000000000604082015260600190565b6020808252600d908201527f494e56414c49445f4e4f4e434500000000000000000000000000000000000000604082015260600190565b60208082526010908201527f53454e4445525f4e4f545f41444d494e00000000000000000000000000000000604082015260600190565b6020808252602e908201527f6f6e6c792061646d696e2063616e207365747570206d6574615472616e73616360408201527f74696f6e50726f636573736f7273000000000000000000000000000000000000606082015260800190565b6020808252600e908201527f494e56414c49445f53454e444552000000000000000000000000000000000000604082015260600190565b6020808252601b908201527f6f6e6c792061646d696e2063616e206368616e67652061646d696e0000000000604082015260600190565b60208082526008908201527f6f766572666c6f77000000000000000000000000000000000000000000000000604082015260600190565b6020808252600e908201527f4e4f545f415554484f52495a4544000000000000000000000000000000000000604082015260600190565b60208082526022908201527f44455354494e4154494f4e5f535441525445525041434b56315f434f4e54524160408201527f4354000000000000000000000000000000000000000000000000000000000000606082015260800190565b60208082526009908201527f64697662797a65726f0000000000000000000000000000000000000000000000604082015260600190565b600060808252612d4e60808301876125ab565b6020830195909552506001600160a01b03929092166040830152606090910152919050565b6fffffffffffffffffffffffffffffffff91909116815260200190565b90815260200190565b6000808335601e19843603018112612daf578283fd5b8084018035925067ffffffffffffffff831115612dca578384fd5b602081019350505060208102360382131561203a57600080fd5b60405181810167ffffffffffffffff81118282101715612e0357600080fd5b604052919050565b600067ffffffffffffffff821115612e21578081fd5b5060209081020190565b6000808335601e19843603018112612e41578283fd5b830160208101925035905067ffffffffffffffff811115612e6157600080fd5b60208102360383131561203a57600080fd5b6001600160a01b0381168114612e8857600080fd5b50565b8015158114612e8857600080fdfea2646970667358221220296d3e08b487c1af2210af37f741a235deffe1d8d1d32d1b04b6ef28c0dfcd8264736f6c63430006050033
[ 9, 12 ]
0x62d315193d750947746a621805db6099179ef48e
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract sbGovernor { event CanceledTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ExecutedTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event QueuedTransaction( bytes32 indexed txHash, address indexed target, uint256 value, string signature, bytes data, uint256 eta ); event ProposalCreated( uint256 id, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); event Voted(address voter, uint256 proposalId, bool support, uint256 votes); event ProposalCanceled(uint256 id); event ProposalQueued(uint256 id, uint256 eta); event ProposalExecuted(uint256 id); using SafeMath for uint256; sbVotesInterface public sbVotes; bool public initDone; address public admin; address public pendingAdmin; address public superAdmin; address public pendingSuperAdmin; uint256 public quorumVotesInWei; uint256 public proposalThresholdInWei; uint256 public proposalMaxOperations; uint256 public votingDelayInBlocks; uint256 public votingPeriodInBlocks; uint256 public queuePeriodInSeconds; uint256 public gracePeriodInSeconds; uint256 public proposalCount; mapping(uint256 => address) public proposalProposer; mapping(uint256 => uint256) public proposalEta; mapping(uint256 => address[]) public proposalTargets; mapping(uint256 => uint256[]) public proposalValues; mapping(uint256 => string[]) public proposalSignatures; mapping(uint256 => bytes[]) public proposalCalldatas; mapping(uint256 => uint256) public proposalStartBlock; mapping(uint256 => uint256) public proposalEndBlock; mapping(uint256 => uint256) public proposalForVotes; mapping(uint256 => uint256) public proposalAgainstVotes; mapping(uint256 => bool) public proposalCanceled; mapping(uint256 => bool) public proposalExecuted; mapping(uint256 => mapping(address => bool)) public proposalVoterHasVoted; mapping(uint256 => mapping(address => bool)) public proposalVoterSupport; mapping(uint256 => mapping(address => uint96)) public proposalVoterVotes; mapping(address => uint256) public latestProposalIds; mapping(bytes32 => bool) public queuedTransactions; mapping(string => uint256) public possibleProposalStatesMapping; string[] public possibleProposalStatesArray; function init( address sbVotesAddress, address adminAddress, address superAdminAddress ) public { require(!initDone, "init done"); sbVotes = sbVotesInterface(sbVotesAddress); admin = adminAddress; superAdmin = superAdminAddress; possibleProposalStatesMapping["Pending"] = 0; possibleProposalStatesArray.push("Pending"); possibleProposalStatesMapping["Active"] = 1; possibleProposalStatesArray.push("Active"); possibleProposalStatesMapping["Canceled"] = 2; possibleProposalStatesArray.push("Canceled"); possibleProposalStatesMapping["Defeated"] = 3; possibleProposalStatesArray.push("Defeated"); possibleProposalStatesMapping["Succeeded"] = 4; possibleProposalStatesArray.push("Succeeded"); possibleProposalStatesMapping["Queued"] = 5; possibleProposalStatesArray.push("Queued"); possibleProposalStatesMapping["Expired"] = 6; possibleProposalStatesArray.push("Expired"); possibleProposalStatesMapping["Executed"] = 7; possibleProposalStatesArray.push("Executed"); initDone = true; } // ADMIN // ************************************************************************************* function setPendingAdmin(address newPendingAdmin) public { require(msg.sender == admin, "not admin"); pendingAdmin = newPendingAdmin; } function acceptAdmin() public { require( msg.sender == pendingAdmin && msg.sender != address(0), "not pendingAdmin" ); admin = pendingAdmin; pendingAdmin = address(0); } function setPendingSuperAdmin(address newPendingSuperAdmin) public { require(msg.sender == superAdmin, "not superAdmin"); pendingSuperAdmin = newPendingSuperAdmin; } function acceptSuperAdmin() public { require( msg.sender == pendingSuperAdmin && msg.sender != address(0), "not pendingSuperAdmin" ); superAdmin = pendingSuperAdmin; pendingSuperAdmin = address(0); } // PARAMETERS // ************************************************************************************* function updateQuorumVotesInWei(uint256 amountInWei) public { require(msg.sender == admin || msg.sender == superAdmin, "not admin"); require(amountInWei > 0, "zero"); quorumVotesInWei = amountInWei; } function updateProposalThresholdInWei(uint256 amountInWei) public { require(msg.sender == admin || msg.sender == superAdmin, "not admin"); require(amountInWei > 0, "zero"); proposalThresholdInWei = amountInWei; } function updateProposalMaxOperations(uint256 count) public { require(msg.sender == admin || msg.sender == superAdmin, "not admin"); require(count > 0, "zero"); proposalMaxOperations = count; } function updateVotingDelayInBlocks(uint256 amountInBlocks) public { require(msg.sender == admin || msg.sender == superAdmin, "not admin"); require(amountInBlocks > 0, "zero"); votingDelayInBlocks = amountInBlocks; } function updateVotingPeriodInBlocks(uint256 amountInBlocks) public { require(msg.sender == admin || msg.sender == superAdmin, "not admin"); require(amountInBlocks > 0, "zero"); votingPeriodInBlocks = amountInBlocks; } function updateQueuePeriodInSeconds(uint256 amountInSeconds) public { require(msg.sender == admin || msg.sender == superAdmin, "not admin"); require(amountInSeconds > 0, "zero"); queuePeriodInSeconds = amountInSeconds; } function updateGracePeriodInSeconds(uint256 amountInSeconds) public { require(msg.sender == admin || msg.sender == superAdmin, "not admin"); require(amountInSeconds > 0, "zero"); gracePeriodInSeconds = amountInSeconds; } // PROPOSALS // ************************************************************************************* function propose( address[] memory targets, uint256[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description ) public returns (uint256) { require( sbVotes.getPriorProposalVotes(msg.sender, block.number.sub(1)) > proposalThresholdInWei, "below threshold" ); require( targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "arity mismatch" ); require(targets.length != 0, "missing actions"); require(targets.length <= proposalMaxOperations, "too many actions"); uint256 latestProposalId = latestProposalIds[msg.sender]; if (latestProposalId != 0) { uint256 proposersLatestProposalState = state(latestProposalId); require( proposersLatestProposalState != possibleProposalStatesMapping["Active"], "already active proposal" ); require( proposersLatestProposalState != possibleProposalStatesMapping["Pending"], "already pending proposal" ); } uint256 startBlock = block.number.add(votingDelayInBlocks); uint256 endBlock = startBlock.add(votingPeriodInBlocks); proposalCount = proposalCount.add(1); proposalProposer[proposalCount] = msg.sender; proposalEta[proposalCount] = 0; proposalTargets[proposalCount] = targets; proposalValues[proposalCount] = values; proposalSignatures[proposalCount] = signatures; proposalCalldatas[proposalCount] = calldatas; proposalStartBlock[proposalCount] = startBlock; proposalEndBlock[proposalCount] = endBlock; proposalForVotes[proposalCount] = 0; proposalAgainstVotes[proposalCount] = 0; proposalCanceled[proposalCount] = false; proposalExecuted[proposalCount] = false; latestProposalIds[msg.sender] = proposalCount; emit ProposalCreated( proposalCount, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description ); return proposalCount; } function vote(uint256 proposalId, bool support) public { return _vote(msg.sender, proposalId, support); } function queue(uint256 proposalId) public { require( state(proposalId) == possibleProposalStatesMapping["Succeeded"], "not succeeded" ); uint256 eta = block.timestamp.add(queuePeriodInSeconds); for (uint256 i = 0; i < proposalTargets[proposalId].length; i++) { _queueOrRevert( proposalTargets[proposalId][i], proposalValues[proposalId][i], proposalSignatures[proposalId][i], proposalCalldatas[proposalId][i], eta ); } proposalEta[proposalId] = eta; emit ProposalQueued(proposalId, eta); } function cancel(uint256 proposalId) public { uint256 state = state(proposalId); require( state != possibleProposalStatesMapping["Executed"], "already executed" ); require( msg.sender == admin || msg.sender == superAdmin || sbVotes.getPriorProposalVotes( proposalProposer[proposalId], block.number.sub(1) ) < proposalThresholdInWei, "below threshold" ); proposalCanceled[proposalId] = true; for (uint256 i = 0; i < proposalTargets[proposalId].length; i++) { _cancelTransaction( proposalTargets[proposalId][i], proposalValues[proposalId][i], proposalSignatures[proposalId][i], proposalCalldatas[proposalId][i], proposalEta[proposalId] ); } emit ProposalCanceled(proposalId); } function execute(uint256 proposalId) public payable { require( state(proposalId) == possibleProposalStatesMapping["Queued"], "not queued" ); proposalExecuted[proposalId] = true; for (uint256 i = 0; i < proposalTargets[proposalId].length; i++) { _executeTransaction( proposalTargets[proposalId][i], proposalValues[proposalId][i], proposalSignatures[proposalId][i], proposalCalldatas[proposalId][i], proposalEta[proposalId] ); } emit ProposalExecuted(proposalId); } function getReceipt(uint256 proposalId, address voter) public view returns ( bool, bool, uint96 ) { return ( proposalVoterHasVoted[proposalId][voter], proposalVoterSupport[proposalId][voter], proposalVoterVotes[proposalId][voter] ); } function getActions(uint256 proposalId) public view returns ( address[] memory, uint256[] memory, string[] memory, bytes[] memory ) { return ( proposalTargets[proposalId], proposalValues[proposalId], proposalSignatures[proposalId], proposalCalldatas[proposalId] ); } function getPossibleProposalStates() public view returns (string[] memory) { return possibleProposalStatesArray; } function getPossibleProposalStateKey(uint256 index) public view returns (string memory) { require(index < possibleProposalStatesArray.length, "invalid index"); return possibleProposalStatesArray[index]; } function state(uint256 proposalId) public view returns (uint256) { require( proposalCount >= proposalId && proposalId > 0, "invalid proposal id" ); if (proposalCanceled[proposalId]) { return possibleProposalStatesMapping["Canceled"]; } else if (block.number <= proposalStartBlock[proposalId]) { return possibleProposalStatesMapping["Pending"]; } else if (block.number <= proposalEndBlock[proposalId]) { return possibleProposalStatesMapping["Active"]; } else if ( proposalForVotes[proposalId] <= proposalAgainstVotes[proposalId] || proposalForVotes[proposalId] < quorumVotesInWei ) { return possibleProposalStatesMapping["Defeated"]; } else if (proposalEta[proposalId] == 0) { return possibleProposalStatesMapping["Succeeded"]; } else if (proposalExecuted[proposalId]) { return possibleProposalStatesMapping["Executed"]; } else if ( block.timestamp >= proposalEta[proposalId].add(gracePeriodInSeconds) ) { return possibleProposalStatesMapping["Expired"]; } else { return possibleProposalStatesMapping["Queued"]; } } // SUPPORT // ************************************************************************************* function _queueOrRevert( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { require( !queuedTransactions[keccak256( abi.encode(target, value, signature, data, eta) )], "already queued at eta" ); _queueTransaction(target, value, signature, data, eta); } function _queueTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal returns (bytes32) { require( eta >= block.timestamp.add(queuePeriodInSeconds), "not satisfy queue period" ); bytes32 txHash = keccak256( abi.encode(target, value, signature, data, eta) ); queuedTransactions[txHash] = true; emit QueuedTransaction(txHash, target, value, signature, data, eta); return txHash; } function _cancelTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal { bytes32 txHash = keccak256( abi.encode(target, value, signature, data, eta) ); queuedTransactions[txHash] = false; emit CanceledTransaction(txHash, target, value, signature, data, eta); } function _executeTransaction( address target, uint256 value, string memory signature, bytes memory data, uint256 eta ) internal returns (bytes memory) { bytes32 txHash = keccak256( abi.encode(target, value, signature, data, eta) ); require(queuedTransactions[txHash], "not queued"); require(block.timestamp >= eta, "not past eta"); require(block.timestamp <= eta.add(gracePeriodInSeconds), "stale"); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked( bytes4(keccak256(bytes(signature))), data ); } (bool success, bytes memory returnData) = target.call{value: value}( callData ); require(success, "execution reverted"); emit ExecutedTransaction(txHash, target, value, signature, data, eta); return returnData; } function _vote( address voter, uint256 proposalId, bool support ) internal { require( state(proposalId) == possibleProposalStatesMapping["Active"], "voting closed" ); require( proposalVoterHasVoted[proposalId][voter] == false, "already voted" ); uint96 votes = sbVotes.getPriorProposalVotes( voter, proposalStartBlock[proposalId] ); if (support) { proposalForVotes[proposalId] = proposalForVotes[proposalId].add( votes ); } else { proposalAgainstVotes[proposalId] = proposalAgainstVotes[proposalId] .add(votes); } proposalVoterHasVoted[proposalId][voter] = true; proposalVoterSupport[proposalId][voter] = support; proposalVoterVotes[proposalId][voter] = votes; emit Voted(voter, proposalId, support, votes); } } interface sbVotesInterface { function getPriorProposalVotes(address account, uint256 blockNumber) external view returns (uint96); function updateVotes( address staker, uint256 rawAmount, bool adding ) external; }
0x6080604052600436106103505760003560e01c8063798f60f2116101c6578063c9d27afe116100f7578063e23a9a5211610095578063f2b065371161006f578063f2b0653714610988578063f851a440146109a8578063fe0d94c1146109bd578063fed0a20e146109d057610350565b8063e23a9a521461092f578063e7f9cefd1461095e578063ecb4452c1461097357610350565b8063da35c664116100d1578063da35c664146108ba578063da95691a146108cf578063ddf0b009146108ef578063de3514b61461090f57610350565b8063c9d27afe1461085a578063ca0c9d791461087a578063d39ca7de1461089a57610350565b8063a7e2286011610164578063b1bb79b11161013e578063b1bb79b1146107cd578063b49d18d6146107ed578063c80a5ba61461081a578063c8bb4dd51461083a57610350565b8063a7e228601461076d578063ab58fb8e1461078d578063ac674664146107ad57610350565b80638faba44c116101a05780638faba44c146106eb5780639d50f36a1461070d5780639dc4e1a01461072d578063a4a53a131461074d57610350565b8063798f60f2146106965780637bdbe4d0146106b6578063878b608d146106cb57610350565b806331078c20116102a05780634e42b06d1161023e57806361fabd051161021857806361fabd051461062c5780636363013a1461064c5780636e18113c1461066157806372cacdd41461068157610350565b80634e42b06d146105bf578063541d1bcc146105ec57806354d7ece41461060c57610350565b806340e58ee51161027a57806340e58ee51461054a5780634147f91d1461056a57806348028d631461058a5780634dd18bf51461059f57610350565b806331078c20146104e5578063328dd982146104fa5780633e4f49e61461052a57610350565b80631684f4551161030d5780631b35b640116102e75780631b35b640146104915780632615a646146104a657806326782247146104bb57806329575f6a146104d057610350565b80631684f4551461043157806317977c6114610451578063184b95591461047157610350565b80630514e6651461035557806308416904146103775780630e18b681146103a2578063103616e8146103b7578063143489d0146103e457806314904b6614610411575b600080fd5b34801561036157600080fd5b50610375610370366004613410565b6109e5565b005b34801561038357600080fd5b5061038c610a52565b6040516103999190613c53565b60405180910390f35b3480156103ae57600080fd5b50610375610a58565b3480156103c357600080fd5b506103d76103d2366004613410565b610ab4565b60405161039991906137f8565b3480156103f057600080fd5b506104046103ff366004613410565b610ac9565b60405161039991906136e3565b34801561041d57600080fd5b506103d761042c366004613463565b610ae4565b34801561043d57600080fd5b5061038c61044c366004613410565b610b04565b34801561045d57600080fd5b5061038c61046c3660046132e4565b610b16565b34801561047d57600080fd5b5061037561048c3660046132ff565b610b28565b34801561049d57600080fd5b5061038c610f25565b3480156104b257600080fd5b5061038c610f2b565b3480156104c757600080fd5b50610404610f31565b3480156104dc57600080fd5b50610404610f40565b3480156104f157600080fd5b5061038c610f4f565b34801561050657600080fd5b5061051a610515366004613410565b610f55565b604051610399949392919061378d565b34801561053657600080fd5b5061038c610545366004613410565b6111e4565b34801561055657600080fd5b50610375610565366004613410565b611367565b34801561057657600080fd5b50610375610585366004613410565b6116e7565b34801561059657600080fd5b5061040461174b565b3480156105ab57600080fd5b506103756105ba3660046132e4565b61175a565b3480156105cb57600080fd5b506105df6105da3660046134c2565b6117a6565b6040516103999190613824565b3480156105f857600080fd5b506105df610607366004613410565b61185a565b34801561061857600080fd5b506105df610627366004613410565b611925565b34801561063857600080fd5b50610375610647366004613410565b611998565b34801561065857600080fd5b5061038c6119fc565b34801561066d57600080fd5b506103d761067c366004613410565b611a02565b34801561068d57600080fd5b50610404611a17565b3480156106a257600080fd5b506103756106b1366004613410565b611a26565b3480156106c257600080fd5b5061038c611a8a565b3480156106d757600080fd5b5061038c6106e63660046134c2565b611a90565b3480156106f757600080fd5b50610700611abe565b60405161039991906137e5565b34801561071957600080fd5b50610375610728366004613410565b611b96565b34801561073957600080fd5b5061038c610748366004613428565b611bfa565b34801561075957600080fd5b506105df6107683660046134c2565b611c17565b34801561077957600080fd5b5061038c610788366004613410565b611c30565b34801561079957600080fd5b5061038c6107a8366004613410565b611c42565b3480156107b957600080fd5b506104046107c83660046134c2565b611c54565b3480156107d957600080fd5b506103756107e8366004613410565b611c89565b3480156107f957600080fd5b5061080d610808366004613463565b611ced565b6040516103999190613d3f565b34801561082657600080fd5b5061038c610835366004613410565b611d13565b34801561084657600080fd5b5061038c610855366004613410565b611d25565b34801561086657600080fd5b5061037561087536600461348f565b611d37565b34801561088657600080fd5b50610375610895366004613410565b611d46565b3480156108a657600080fd5b506103756108b53660046132e4565b611daa565b3480156108c657600080fd5b5061038c611df6565b3480156108db57600080fd5b5061038c6108ea366004613344565b611dfc565b3480156108fb57600080fd5b5061037561090a366004613410565b612193565b34801561091b57600080fd5b506103d761092a366004613463565b612417565b34801561093b57600080fd5b5061094f61094a366004613463565b612437565b60405161039993929190613803565b34801561096a57600080fd5b5061037561249c565b34801561097f57600080fd5b5061038c6124f8565b34801561099457600080fd5b506103d76109a3366004613410565b6124fe565b3480156109b457600080fd5b50610404612513565b6103756109cb366004613410565b612522565b3480156109dc57600080fd5b506103d76127ac565b6001546001600160a01b0316331480610a0857506003546001600160a01b031633145b610a2d5760405162461bcd60e51b8152600401610a2490613be3565b60405180910390fd5b60008111610a4d5760405162461bcd60e51b8152600401610a24906138ec565b600b55565b600b5481565b6002546001600160a01b031633148015610a7157503315155b610a8d5760405162461bcd60e51b8152600401610a24906139d4565b60028054600180546001600160a01b03199081166001600160a01b03841617909155169055565b60186020526000908152604090205460ff1681565b600d602052600090815260409020546001600160a01b031681565b601960209081526000928352604080842090915290825290205460ff1681565b60146020526000908152604090205481565b601c6020526000908152604090205481565b600054600160a01b900460ff1615610b525760405162461bcd60e51b8152600401610a24906139b1565b600080546001600160a01b038086166001600160a01b0319928316178355600180548683169084161790556003805491851691909216179055604051601e90610b9a90613671565b908152604080516020928190038301812093909355601f805460018101825560009190915283820190915260078084526650656e64696e6760c81b92909301918252610bf992600080516020613dcb8339815191529091019190612e60565b506001601e604051610c0a906136be565b908152604080516020928190038301812093909355601f805460018101825560009190915283820190915260068084526541637469766560d01b92909301918252610c6892600080516020613dcb8339815191529091019190612e60565b506002601e604051610c79906136aa565b908152604080516020928190038301812093909355601f805460018101825560009190915283820190915260088084526710d85b98d95b195960c21b92909301918252610cd992600080516020613dcb8339815191529091019190612e60565b506003601e604051610cea90613696565b908152604080516020928190038301812093909355601f805460018101825560009190915283820190915260088084526711195999585d195960c21b92909301918252610d4a92600080516020613dcb8339815191529091019190612e60565b506004601e604051610d5b9061365c565b908152604080516020928190038301812093909355601f805460018101825560009190915283820190915260098084526814dd58d8d95959195960ba1b92909301918252610dbc92600080516020613dcb8339815191529091019190612e60565b506005601e604051610dcd90613684565b908152604080516020928190038301812093909355601f8054600181018255600091909152838201909152600680845265145d595d595960d21b92909301918252610e2b92600080516020613dcb8339815191529091019190612e60565b506006601e604051610e3c906136d0565b908152604080516020928190038301812093909355601f8054600181018255600091909152838201909152600780845266115e1c1a5c995960ca1b92909301918252610e9b92600080516020613dcb8339815191529091019190612e60565b506007601e604051610eac90613648565b908152604080516020928190038301812093909355601f8054600181018255600091909152838201909152600880845267115e1958dd5d195960c21b92909301918252610f0c92600080516020613dcb8339815191529091019190612e60565b50506000805460ff60a01b1916600160a01b1790555050565b60085481565b60095481565b6002546001600160a01b031681565b6003546001600160a01b031681565b60065481565b6000818152600f60209081526040808320601083528184206011845282852060128552948390208254845181870281018701909552808552606096879687968796959492939091869190830182828015610fd857602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610fba575b505050505093508280548060200260200160405190810160405280929190818152602001828054801561102a57602002820191906000526020600020905b815481526020019060010190808311611016575b5050505050925081805480602002602001604051908101604052809291908181526020016000905b828210156110fd5760008481526020908190208301805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156110e95780601f106110be576101008083540402835291602001916110e9565b820191906000526020600020905b8154815290600101906020018083116110cc57829003601f168201915b505050505081526020019060010190611052565b50505050915080805480602002602001604051908101604052809291908181526020016000905b828210156111cf5760008481526020908190208301805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156111bb5780601f10611190576101008083540402835291602001916111bb565b820191906000526020600020905b81548152906001019060200180831161119e57829003601f168201915b505050505081526020019060010190611124565b50505050905093509350935093509193509193565b600081600c54101580156111f85750600082115b6112145760405162461bcd60e51b8152600401610a24906138bf565b60008281526017602052604090205460ff161561124f57601e604051611239906136aa565b9081526020016040518091039020549050611362565b600082815260136020526040902054431161127257601e60405161123990613671565b600082815260146020526040902054431161129557601e604051611239906136be565b6000828152601660209081526040808320546015909252909120541115806112cc5750600554600083815260156020526040902054105b156112df57601e60405161123990613696565b6000828152600e602052604090205461130057601e6040516112399061365c565b60008281526018602052604090205460ff161561132557601e60405161123990613648565b600b546000838152600e6020526040902054611340916127bc565b421061135457601e604051611239906136d0565b601e60405161123990613684565b919050565b6000611372826111e4565b9050601e60405161138290613648565b9081526020016040518091039020548114156113b05760405162461bcd60e51b8152600401610a2490613a7b565b6001546001600160a01b03163314806113d357506003546001600160a01b031633145b80611484575060065460008054848252600d6020526040909120546001600160a01b039182169163916c435f911661140c4360016127ea565b6040518363ffffffff1660e01b81526004016114299291906136f7565b60206040518083038186803b15801561144157600080fd5b505afa158015611455573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061147991906134e3565b6001600160601b0316105b6114a05760405162461bcd60e51b8152600401610a2490613837565b6000828152601760205260408120805460ff191660011790555b6000838152600f60205260409020548110156116ab576000838152600f6020526040902080546116a39190839081106114ef57fe5b60009182526020808320909101548683526010909152604090912080546001600160a01b03909216918490811061152257fe5b906000526020600020015460116000878152602001908152602001600020848154811061154b57fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156115d95780601f106115ae576101008083540402835291602001916115d9565b820191906000526020600020905b8154815290600101906020018083116115bc57829003601f168201915b5050506000898152601260205260409020805490925087915081106115fa57fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156116885780601f1061165d57610100808354040283529160200191611688565b820191906000526020600020905b81548152906001019060200180831161166b57829003601f168201915b50505060008a8152600e6020526040902054915061282c9050565b6001016114ba565b507f789cf55be980739dad1d0699b93b58e806b51c9d96619bfa8fe0a28abaa7b30c826040516116db9190613c53565b60405180910390a15050565b6001546001600160a01b031633148061170a57506003546001600160a01b031633145b6117265760405162461bcd60e51b8152600401610a2490613be3565b600081116117465760405162461bcd60e51b8152600401610a24906138ec565b600955565b6004546001600160a01b031681565b6001546001600160a01b031633146117845760405162461bcd60e51b8152600401610a2490613be3565b600280546001600160a01b0319166001600160a01b0392909216919091179055565b601260205281600052604060002081815481106117bf57fe5b600091825260209182902001805460408051601f600260001961010060018716150201909416939093049283018590048502810185019091528181529450909250908301828280156118525780601f1061182757610100808354040283529160200191611852565b820191906000526020600020905b81548152906001019060200180831161183557829003601f168201915b505050505081565b601f54606090821061187e5760405162461bcd60e51b8152600401610a2490613c2c565b601f828154811061188b57fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156119195780601f106118ee57610100808354040283529160200191611919565b820191906000526020600020905b8154815290600101906020018083116118fc57829003601f168201915b50505050509050919050565b601f818154811061193257fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152935090918301828280156118525780601f1061182757610100808354040283529160200191611852565b6001546001600160a01b03163314806119bb57506003546001600160a01b031633145b6119d75760405162461bcd60e51b8152600401610a2490613be3565b600081116119f75760405162461bcd60e51b8152600401610a24906138ec565b600755565b60055481565b60176020526000908152604090205460ff1681565b6000546001600160a01b031681565b6001546001600160a01b0316331480611a4957506003546001600160a01b031633145b611a655760405162461bcd60e51b8152600401610a2490613be3565b60008111611a855760405162461bcd60e51b8152600401610a24906138ec565b600855565b60075481565b60106020528160005260406000208181548110611aa957fe5b90600052602060002001600091509150505481565b6060601f805480602002602001604051908101604052809291908181526020016000905b82821015611b8d5760008481526020908190208301805460408051601f6002600019610100600187161502019094169390930492830185900485028101850190915281815292830182828015611b795780601f10611b4e57610100808354040283529160200191611b79565b820191906000526020600020905b815481529060010190602001808311611b5c57829003601f168201915b505050505081526020019060010190611ae2565b50505050905090565b6001546001600160a01b0316331480611bb957506003546001600160a01b031633145b611bd55760405162461bcd60e51b8152600401610a2490613be3565b60008111611bf55760405162461bcd60e51b8152600401610a24906138ec565b600655565b8051602081830181018051601e8252928201919093012091525481565b601160205281600052604060002081815481106117bf57fe5b60166020526000908152604090205481565b600e6020526000908152604090205481565b600f6020528160005260406000208181548110611c6d57fe5b6000918252602090912001546001600160a01b03169150829050565b6001546001600160a01b0316331480611cac57506003546001600160a01b031633145b611cc85760405162461bcd60e51b8152600401610a2490613be3565b60008111611ce85760405162461bcd60e51b8152600401610a24906138ec565b600555565b601b6020908152600092835260408084209091529082529020546001600160601b031681565b60136020526000908152604090205481565b60156020526000908152604090205481565b611d423383836128c6565b5050565b6001546001600160a01b0316331480611d6957506003546001600160a01b031633145b611d855760405162461bcd60e51b8152600401610a2490613be3565b60008111611da55760405162461bcd60e51b8152600401610a24906138ec565b600a55565b6003546001600160a01b03163314611dd45760405162461bcd60e51b8152600401610a2490613b92565b600480546001600160a01b0319166001600160a01b0392909216919091179055565b600c5481565b600654600080549091906001600160a01b031663916c435f33611e204360016127ea565b6040518363ffffffff1660e01b8152600401611e3d9291906136f7565b60206040518083038186803b158015611e5557600080fd5b505afa158015611e69573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e8d91906134e3565b6001600160601b031611611eb35760405162461bcd60e51b8152600401610a2490613837565b84518651148015611ec5575083518651145b8015611ed2575082518651145b611eee5760405162461bcd60e51b8152600401610a2490613897565b8551611f0c5760405162461bcd60e51b8152600401610a2490613bba565b60075486511115611f2f5760405162461bcd60e51b8152600401610a2490613968565b336000908152601c60205260409020548015611fcc576000611f50826111e4565b9050601e604051611f60906136be565b908152602001604051809103902054811415611f8e5760405162461bcd60e51b8152600401610a2490613aa5565b601e604051611f9c90613671565b908152602001604051809103902054811415611fca5760405162461bcd60e51b8152600401610a2490613b5b565b505b6000611fe3600854436127bc90919063ffffffff16565b90506000611ffc600954836127bc90919063ffffffff16565b600c5490915061200d9060016127bc565b600c8181556000918252600d6020908152604080842080546001600160a01b0319163317905582548452600e825280842084905591548352600f815291208a51612059928c0190612ede565b50600c546000908152601060209081526040909120895161207c928b0190612f3f565b50600c546000908152601160209081526040909120885161209f928a0190612f79565b50600c54600090815260126020908152604090912087516120c292890190612fd2565b50600c805460009081526013602090815260408083208690558354835260148252808320859055835483526015825280832083905583548352601682528083208390558354835260178252808320805460ff19908116909155845484526018835281842080549091169055925433808452601c9092529183902082905591517f7d84a6263ae0d98d3329bd7b46bb4e8d6f98cd35a7adb45c274c8b7fd5ebd5e09261217b92918d908d908d908d908a908a908f90613c5c565b60405180910390a15050600c54979650505050505050565b601e6040516121a19061365c565b9081526020016040518091039020546121b9826111e4565b146121d65760405162461bcd60e51b8152600401610a2490613a2d565b60006121ed600a54426127bc90919063ffffffff16565b905060005b6000838152600f60205260409020548110156123d3576000838152600f6020526040902080546123cb91908390811061222757fe5b60009182526020808320909101548683526010909152604090912080546001600160a01b03909216918490811061225a57fe5b906000526020600020015460116000878152602001908152602001600020848154811061228357fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156123115780601f106122e657610100808354040283529160200191612311565b820191906000526020600020905b8154815290600101906020018083116122f457829003601f168201915b50505060008981526012602052604090208054909250879150811061233257fe5b600091825260209182902001805460408051601f60026000196101006001871615020190941693909304928301859004850281018501909152818152928301828280156123c05780601f10612395576101008083540402835291602001916123c0565b820191906000526020600020905b8154815290600101906020018083116123a357829003601f168201915b505050505086612b0e565b6001016121f2565b506000828152600e602052604090819020829055517f9a2e42fd6722813d69113e7d0079d3d940171428df7373df9c7f7617cfda2892906116db9084908490613d31565b601a60209081526000928352604080842090915290825290205460ff1681565b60008281526019602090815260408083206001600160a01b039490941680845293825280832054858452601a8352818420858552835281842054958452601b83528184209484529390915290205460ff9182169391909216916001600160601b031690565b6004546001600160a01b0316331480156124b557503315155b6124d15760405162461bcd60e51b8152600401610a24906139fe565b60048054600380546001600160a01b03199081166001600160a01b03841617909155169055565b600a5481565b601d6020526000908152604090205460ff1681565b6001546001600160a01b031681565b601e60405161253090613684565b908152602001604051809103902054612548826111e4565b146125655760405162461bcd60e51b8152600401610a2490613b37565b6000818152601860205260408120805460ff191660011790555b6000828152600f6020526040902054811015612771576000828152600f6020526040902080546127689190839081106125b457fe5b60009182526020808320909101548583526010909152604090912080546001600160a01b0390921691849081106125e757fe5b906000526020600020015460116000868152602001908152602001600020848154811061261057fe5b600091825260209182902001805460408051601f600260001961010060018716150201909416939093049283018590048502810185019091528181529283018282801561269e5780601f106126735761010080835404028352916020019161269e565b820191906000526020600020905b81548152906001019060200180831161268157829003601f168201915b5050506000888152601260205260409020805490925087915081106126bf57fe5b600091825260209182902001805460408051601f600260001961010060018716150201909416939093049283018590048502810185019091528181529283018282801561274d5780601f106127225761010080835404028352916020019161274d565b820191906000526020600020905b81548152906001019060200180831161273057829003601f168201915b5050506000898152600e60205260409020549150612b869050565b5060010161257f565b507f712ae1383f79ac853f8d882153778e0260ef8f03b504e2866e0593e04d2b291f816040516127a19190613c53565b60405180910390a150565b600054600160a01b900460ff1681565b6000828201838110156127e15760405162461bcd60e51b8152600401610a2490613931565b90505b92915050565b60006127e183836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250612d5f565b60008585858585604051602001612847959493929190613741565b60408051601f1981840301815282825280516020918201206000818152601d909252919020805460ff1916905591506001600160a01b0387169082907f823ab24d921488c1644a7cc13dab2df44d40887e849890fc6a86effa299c9d1d906128b6908990899089908990613cf4565b60405180910390a3505050505050565b601e6040516128d4906136be565b9081526020016040518091039020546128ec836111e4565b146129095760405162461bcd60e51b8152600401610a2490613a54565b60008281526019602090815260408083206001600160a01b038716845290915290205460ff161561294c5760405162461bcd60e51b8152600401610a249061390a565b600080548382526013602052604080832054905163916c435f60e01b81526001600160a01b039092169163916c435f9161298b918891906004016136f7565b60206040518083038186803b1580156129a357600080fd5b505afa1580156129b7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129db91906134e3565b90508115612a1957600083815260156020526040902054612a05906001600160601b0383166127bc565b600084815260156020526040902055612a4b565b600083815260166020526040902054612a3b906001600160601b0383166127bc565b6000848152601660205260409020555b60008381526019602090815260408083206001600160a01b0388168085529083528184208054600160ff1991821617909155878552601a845282852082865284528285208054909116871515179055868452601b83528184209084529091529081902080546bffffffffffffffffffffffff19166001600160601b038416179055517f9fea94799b68dbb994c4e44547ea7b5c9e4068fbc385b8b688005a16b60c3cc690612b00908690869086908690613710565b60405180910390a150505050565b601d60008686868686604051602001612b2b959493929190613741565b60408051601f198184030181529181528151602092830120835290820192909252016000205460ff1615612b715760405162461bcd60e51b8152600401610a2490613b08565b612b7e8585858585612d8b565b505050505050565b606060008686868686604051602001612ba3959493929190613741565b60408051601f1981840301815291815281516020928301206000818152601d90935291205490915060ff16612bea5760405162461bcd60e51b8152600401610a2490613b37565b82421015612c0a5760405162461bcd60e51b8152600401610a2490613c06565b600b54612c189084906127bc565b421115612c375760405162461bcd60e51b8152600401610a2490613992565b6000818152601d60205260409020805460ff191690558451606090612c5d575083612c89565b858051906020012085604051602001612c779291906135fb565b60405160208183030381529060405290505b60006060896001600160a01b03168984604051612ca6919061362c565b60006040518083038185875af1925050503d8060008114612ce3576040519150601f19603f3d011682016040523d82523d6000602084013e612ce8565b606091505b509150915081612d0a5760405162461bcd60e51b8152600401610a2490613adc565b896001600160a01b0316847fae7b1f84eb1b45a5f46a86b5895ec3bf0c66f223fa8185dc777fc81d6a9602c28b8b8b8b604051612d4a9493929190613cf4565b60405180910390a39998505050505050505050565b60008184841115612d835760405162461bcd60e51b8152600401610a249190613824565b505050900390565b6000612da2600a54426127bc90919063ffffffff16565b821015612dc15760405162461bcd60e51b8152600401610a2490613860565b60008686868686604051602001612ddc959493929190613741565b60408051601f1981840301815282825280516020918201206000818152601d909252919020805460ff1916600117905591506001600160a01b0388169082907fc91d82514b5af1b7f210f0c8ed6d0a832e34eefd3ca60d3d909a4cff1d248f6590612e4e908a908a908a908a90613cf4565b60405180910390a39695505050505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10612ea157805160ff1916838001178555612ece565b82800160010185558215612ece579182015b82811115612ece578251825591602001919060010190612eb3565b50612eda92915061302b565b5090565b828054828255906000526020600020908101928215612f33579160200282015b82811115612f3357825182546001600160a01b0319166001600160a01b03909116178255602090920191600190910190612efe565b50612eda929150613040565b828054828255906000526020600020908101928215612ece5791602002820182811115612ece578251825591602001919060010190612eb3565b828054828255906000526020600020908101928215612fc6579160200282015b82811115612fc65782518051612fb6918491602090910190612e60565b5091602001919060010190612f99565b50612eda92915061305f565b82805482825590600052602060002090810192821561301f579160200282015b8281111561301f578251805161300f918491602090910190612e60565b5091602001919060010190612ff2565b50612eda92915061307c565b5b80821115612eda576000815560010161302c565b5b80821115612eda5780546001600160a01b0319168155600101613041565b80821115612eda5760006130738282613099565b5060010161305f565b80821115612eda5760006130908282613099565b5060010161307c565b50805460018160011615610100020316600290046000825580601f106130bf57506130dd565b601f0160209004906000526020600020908101906130dd919061302b565b50565b80356001600160a01b03811681146127e457600080fd5b600082601f830112613107578081fd5b813561311a61311582613d7a565b613d53565b81815291506020808301908481018184028601820187101561313b57600080fd5b60005b848110156131625761315088836130e0565b8452928201929082019060010161313e565b505050505092915050565b600082601f83011261317d578081fd5b813561318b61311582613d7a565b818152915060208083019084810160005b84811015613162576131b3888484358a010161327b565b8452928201929082019060010161319c565b600082601f8301126131d5578081fd5b81356131e361311582613d7a565b818152915060208083019084810160005b848110156131625761320b888484358a010161327b565b845292820192908201906001016131f4565b600082601f83011261322d578081fd5b813561323b61311582613d7a565b81815291506020808301908481018184028601820187101561325c57600080fd5b60005b848110156131625781358452928201929082019060010161325f565b600082601f83011261328b578081fd5b813567ffffffffffffffff8111156132a1578182fd5b6132b4601f8201601f1916602001613d53565b91508082528360208285010111156132cb57600080fd5b8060208401602084013760009082016020015292915050565b6000602082840312156132f5578081fd5b6127e183836130e0565b600080600060608486031215613313578182fd5b61331d85856130e0565b925061332c85602086016130e0565b915061333b85604086016130e0565b90509250925092565b600080600080600060a0868803121561335b578081fd5b853567ffffffffffffffff80821115613372578283fd5b61337e89838a016130f7565b96506020880135915080821115613393578283fd5b61339f89838a0161321d565b955060408801359150808211156133b4578283fd5b6133c089838a016131c5565b945060608801359150808211156133d5578283fd5b6133e189838a0161316d565b935060808801359150808211156133f6578283fd5b506134038882890161327b565b9150509295509295909350565b600060208284031215613421578081fd5b5035919050565b600060208284031215613439578081fd5b813567ffffffffffffffff81111561344f578182fd5b61345b8482850161327b565b949350505050565b60008060408385031215613475578182fd5b8235915061348684602085016130e0565b90509250929050565b600080604083850312156134a1578182fd5b82359150602083013580151581146134b7578182fd5b809150509250929050565b600080604083850312156134d4578182fd5b50508035926020909101359150565b6000602082840312156134f4578081fd5b81516001600160601b03811681146127e1578182fd5b6000815180845260208085019450808401835b838110156135425781516001600160a01b03168752958201959082019060010161351d565b509495945050505050565b6000815180845260208085018081965082840281019150828601855b858110156135935782840389526135818483516135cf565b98850198935090840190600101613569565b5091979650505050505050565b6000815180845260208085019450808401835b83811015613542578151875295820195908201906001016135b3565b600081518084526135e7816020860160208601613d9a565b601f01601f19169290920160200192915050565b6001600160e01b031983168152815160009061361e816004850160208701613d9a565b919091016004019392505050565b6000825161363e818460208701613d9a565b9190910192915050565b67115e1958dd5d195960c21b815260080190565b6814dd58d8d95959195960ba1b815260090190565b6650656e64696e6760c81b815260070190565b65145d595d595960d21b815260060190565b6711195999585d195960c21b815260080190565b6710d85b98d95b195960c21b815260080190565b6541637469766560d01b815260060190565b66115e1c1a5c995960ca1b815260070190565b6001600160a01b0391909116815260200190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b039490941684526020840192909252151560408301526001600160601b0316606082015260800190565b600060018060a01b038716825285602083015260a0604083015261376860a08301866135cf565b828103606084015261377a81866135cf565b9150508260808301529695505050505050565b6000608082526137a0608083018761350a565b82810360208401526137b281876135a0565b905082810360408401526137c6818661354d565b905082810360608401526137da818561354d565b979650505050505050565b6000602082526127e1602083018461354d565b901515815260200190565b921515835290151560208301526001600160601b0316604082015260600190565b6000602082526127e160208301846135cf565b6020808252600f908201526e18995b1bddc81d1a1c995cda1bdb19608a1b604082015260600190565b60208082526018908201527f6e6f74207361746973667920717565756520706572696f640000000000000000604082015260600190565b6020808252600e908201526d0c2e4d2e8f240dad2e6dac2e8c6d60931b604082015260600190565b6020808252601390820152721a5b9d985b1a59081c1c9bdc1bdcd85b081a59606a1b604082015260600190565b6020808252600490820152637a65726f60e01b604082015260600190565b6020808252600d908201526c185b1c9958591e481d9bdd1959609a1b604082015260600190565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b60208082526010908201526f746f6f206d616e7920616374696f6e7360801b604082015260600190565b6020808252600590820152647374616c6560d81b604082015260600190565b602080825260099082015268696e697420646f6e6560b81b604082015260600190565b60208082526010908201526f3737ba103832b73234b733a0b236b4b760811b604082015260600190565b6020808252601590820152743737ba103832b73234b733a9bab832b920b236b4b760591b604082015260600190565b6020808252600d908201526c1b9bdd081cdd58d8d959591959609a1b604082015260600190565b6020808252600d908201526c1d9bdd1a5b99c818db1bdcd959609a1b604082015260600190565b60208082526010908201526f185b1c9958591e48195e1958dd5d195960821b604082015260600190565b60208082526017908201527f616c7265616479206163746976652070726f706f73616c000000000000000000604082015260600190565b602080825260129082015271195e1958dd5d1a5bdb881c995d995c9d195960721b604082015260600190565b602080825260159082015274616c7265616479207175657565642061742065746160581b604082015260600190565b6020808252600a90820152691b9bdd081c5d595d595960b21b604082015260600190565b60208082526018908201527f616c72656164792070656e64696e672070726f706f73616c0000000000000000604082015260600190565b6020808252600e908201526d3737ba1039bab832b920b236b4b760911b604082015260600190565b6020808252600f908201526e6d697373696e6720616374696f6e7360881b604082015260600190565b6020808252600990820152683737ba1030b236b4b760b91b604082015260600190565b6020808252600c908201526b6e6f7420706173742065746160a01b604082015260600190565b6020808252600d908201526c0d2dcecc2d8d2c840d2dcc8caf609b1b604082015260600190565b90815260200190565b8981526001600160a01b038916602082015261012060408201819052600090613c878382018b61350a565b90508281036060840152613c9b818a6135a0565b90508281036080840152613caf818961354d565b905082810360a0840152613cc3818861354d565b90508560c08401528460e0840152828103610100840152613ce481856135cf565b9c9b505050505050505050505050565b600085825260806020830152613d0d60808301866135cf565b8281036040840152613d1f81866135cf565b91505082606083015295945050505050565b918252602082015260400190565b6001600160601b0391909116815260200190565b60405181810167ffffffffffffffff81118282101715613d7257600080fd5b604052919050565b600067ffffffffffffffff821115613d90578081fd5b5060209081020190565b60005b83811015613db5578181015183820152602001613d9d565b83811115613dc4576000848401525b5050505056fea03837a25210ee280c2113ff4b77ca23440b19d4866cca721c801278fd08d807a26469706673582212206e417dd5665fbc9d890a8db74b4f570959926e998d42d4e20362e44acd4c35b364736f6c634300060c0033
[ 9 ]
0x62EE90d75f1BEc074A32160C7Ce3F30b999764Db
pragma solidity 0.5.17; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _txOrigin() internal view returns (address payable) { return tx.origin; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20Upgrade { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ // function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ // function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed _owner, address indexed spender, uint256 value); } interface IEnergiTokenUpgrade2 { function owner() external view returns (address); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function initialized() external view returns (bool); function vault() external view returns (address); function minRedemptionAmount() external view returns (uint); function upgradeInitialized() external view returns (bool); function setOwner(address _owner) external; function setSymbol(string calldata _symbol) external; function setVault(address _vault) external; function setMinRedemptionAmount(uint _minRedemptionAmount) external; function mint(address recipient, uint amount) external; function burn(address recipient, uint amount) external; function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract ERC20Upgrade is Context, IERC20Upgrade { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ // function transfer(address recipient, uint256 amount) public returns (bool) { // _transfer(_msgSender(), recipient, amount); // return true; // } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ // function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { // _transfer(sender, recipient, amount); // _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); // return true; // } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract EnergiTokenUpgrade2 is ERC20Upgrade, IEnergiTokenUpgrade2 { address public owner; // Initialised on previous impl string public name; // Initialised on previous impl string public symbol; // Initialised on previous impl uint8 public decimals; // Initialised on previous impl bool public initialized = true; // Previous impl was already initialised address public vault; // Initialised on previous impl uint public minRedemptionAmount; // Initialised on previous impl bool public upgradeInitialized = true; // Previous upgrade was already initialised modifier onlyOwner { require(msg.sender == owner, 'EnergiToken: FORBIDDEN'); _; } function setOwner(address _owner) external onlyOwner { owner = _owner; } function setName(string calldata _name) external onlyOwner { name = _name; } function setSymbol(string calldata _symbol) external onlyOwner { symbol = _symbol; } function setVault(address _vault) external onlyOwner { vault = _vault; } function setMinRedemptionAmount(uint _minRedemptionAmount) external onlyOwner { minRedemptionAmount = _minRedemptionAmount; } function mint(address recipient, uint amount) external onlyOwner { _mint(recipient, amount); } function burn(address recipient, uint amount) external onlyOwner { _burn(recipient, amount); } function transfer(address recipient, uint256 amount) external returns (bool) { if(recipient == vault) { require(amount >= minRedemptionAmount, "EnergiToken: redemption amount too small"); } _transfer(_msgSender(), recipient, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { if(recipient == vault) { require(amount >= minRedemptionAmount, "EnergiToken: redemption amount too small"); } _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } }
0x608060405234801561001057600080fd5b506004361061014d5760003560e01c8063695d3985116100c3578063a457c2d71161007c578063a457c2d7146103d6578063a9059cbb14610402578063b84c82461461042e578063c47f00271461049e578063dd62ed3e1461050e578063fbfa77cf1461053c5761014d565b8063695d39851461034857806370a08231146103505780638da5cb5b1461037657806395d89b411461039a5780639dc29fac146103a25780639f027e73146103ce5761014d565b806323b872dd1161011557806323b872dd14610259578063313ce5671461028f57806339509351146102ad57806340c10f19146102d9578063464f2e99146103055780636817031b146103225761014d565b806306fdde0314610152578063095ea7b3146101cf57806313af40351461020f578063158ef93e1461023757806318160ddd1461023f575b600080fd5b61015a610544565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561019457818101518382015260200161017c565b50505050905090810190601f1680156101c15780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101fb600480360360408110156101e557600080fd5b506001600160a01b0381351690602001356105d2565b604080519115158252519081900360200190f35b6102356004803603602081101561022557600080fd5b50356001600160a01b03166105ef565b005b6101fb61065e565b61024761066c565b60408051918252519081900360200190f35b6101fb6004803603606081101561026f57600080fd5b506001600160a01b03813581169160208101359091169060400135610673565b61029761075e565b6040805160ff9092168252519081900360200190f35b6101fb600480360360408110156102c357600080fd5b506001600160a01b038135169060200135610767565b610235600480360360408110156102ef57600080fd5b506001600160a01b0381351690602001356107bb565b6102356004803603602081101561031b57600080fd5b5035610816565b6102356004803603602081101561033857600080fd5b50356001600160a01b0316610868565b6101fb6108df565b6102476004803603602081101561036657600080fd5b50356001600160a01b03166108e8565b61037e610903565b604080516001600160a01b039092168252519081900360200190f35b61015a610912565b610235600480360360408110156103b857600080fd5b506001600160a01b03813516906020013561096d565b6102476109c4565b6101fb600480360360408110156103ec57600080fd5b506001600160a01b0381351690602001356109ca565b6101fb6004803603604081101561041857600080fd5b506001600160a01b038135169060200135610a38565b6102356004803603602081101561044457600080fd5b81019060208101813564010000000081111561045f57600080fd5b82018360208201111561047157600080fd5b8035906020019184600183028401116401000000008311171561049357600080fd5b509092509050610aaa565b610235600480360360208110156104b457600080fd5b8101906020810181356401000000008111156104cf57600080fd5b8201836020820111156104e157600080fd5b8035906020019184600183028401116401000000008311171561050357600080fd5b509092509050610b08565b6102476004803603604081101561052457600080fd5b506001600160a01b0381358116916020013516610b61565b61037e610b8c565b6004805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105ca5780601f1061059f576101008083540402835291602001916105ca565b820191906000526020600020905b8154815290600101906020018083116105ad57829003601f168201915b505050505081565b60006105e66105df610ba1565b8484610ba5565b50600192915050565b6003546001600160a01b0316331461063c576040805162461bcd60e51b81526020600482015260166024820152600080516020611261833981519152604482015290519081900360640190fd5b600380546001600160a01b0319166001600160a01b0392909216919091179055565b600654610100900460ff1681565b6002545b90565b6006546000906001600160a01b03848116620100009092041614156106d3576007548210156106d35760405162461bcd60e51b81526004018080602001828103825260288152602001806111cf6028913960400191505060405180910390fd5b6106de848484610c91565b610754846106ea610ba1565b61074f85604051806060016040528060288152602001611281602891396001600160a01b038a16600090815260016020526040812090610728610ba1565b6001600160a01b03168152602081019190915260400160002054919063ffffffff610ded16565b610ba5565b5060019392505050565b60065460ff1681565b60006105e6610774610ba1565b8461074f8560016000610785610ba1565b6001600160a01b03908116825260208083019390935260409182016000908120918c16815292529020549063ffffffff610e8416565b6003546001600160a01b03163314610808576040805162461bcd60e51b81526020600482015260166024820152600080516020611261833981519152604482015290519081900360640190fd5b6108128282610ee5565b5050565b6003546001600160a01b03163314610863576040805162461bcd60e51b81526020600482015260166024820152600080516020611261833981519152604482015290519081900360640190fd5b600755565b6003546001600160a01b031633146108b5576040805162461bcd60e51b81526020600482015260166024820152600080516020611261833981519152604482015290519081900360640190fd5b600680546001600160a01b03909216620100000262010000600160b01b0319909216919091179055565b60085460ff1681565b6001600160a01b031660009081526020819052604090205490565b6003546001600160a01b031681565b6005805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105ca5780601f1061059f576101008083540402835291602001916105ca565b6003546001600160a01b031633146109ba576040805162461bcd60e51b81526020600482015260166024820152600080516020611261833981519152604482015290519081900360640190fd5b6108128282610fd5565b60075481565b60006105e66109d7610ba1565b8461074f856040518060600160405280602581526020016113136025913960016000610a01610ba1565b6001600160a01b03908116825260208083019390935260409182016000908120918d1681529252902054919063ffffffff610ded16565b6006546000906001600160a01b0384811662010000909204161415610a9857600754821015610a985760405162461bcd60e51b81526004018080602001828103825260288152602001806111cf6028913960400191505060405180910390fd5b6105e6610aa3610ba1565b8484610c91565b6003546001600160a01b03163314610af7576040805162461bcd60e51b81526020600482015260166024820152600080516020611261833981519152604482015290519081900360640190fd5b610b0360058383611113565b505050565b6003546001600160a01b03163314610b55576040805162461bcd60e51b81526020600482015260166024820152600080516020611261833981519152604482015290519081900360640190fd5b610b0360048383611113565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6006546201000090046001600160a01b031681565b3390565b6001600160a01b038316610bea5760405162461bcd60e51b81526004018080602001828103825260248152602001806112ef6024913960400191505060405180910390fd5b6001600160a01b038216610c2f5760405162461bcd60e51b81526004018080602001828103825260228152602001806112196022913960400191505060405180910390fd5b6001600160a01b03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b6001600160a01b038316610cd65760405162461bcd60e51b81526004018080602001828103825260258152602001806112ca6025913960400191505060405180910390fd5b6001600160a01b038216610d1b5760405162461bcd60e51b81526004018080602001828103825260238152602001806111ac6023913960400191505060405180910390fd5b610d5e8160405180606001604052806026815260200161123b602691396001600160a01b038616600090815260208190526040902054919063ffffffff610ded16565b6001600160a01b038085166000908152602081905260408082209390935590841681522054610d93908263ffffffff610e8416565b6001600160a01b038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b60008184841115610e7c5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b83811015610e41578181015183820152602001610e29565b50505050905090810190601f168015610e6e5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b505050900390565b600082820183811015610ede576040805162461bcd60e51b815260206004820152601b60248201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604482015290519081900360640190fd5b9392505050565b6001600160a01b038216610f40576040805162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015290519081900360640190fd5b600254610f53908263ffffffff610e8416565b6002556001600160a01b038216600090815260208190526040902054610f7f908263ffffffff610e8416565b6001600160a01b0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6001600160a01b03821661101a5760405162461bcd60e51b81526004018080602001828103825260218152602001806112a96021913960400191505060405180910390fd5b61105d816040518060600160405280602281526020016111f7602291396001600160a01b038516600090815260208190526040902054919063ffffffff610ded16565b6001600160a01b038316600090815260208190526040902055600254611089908263ffffffff6110d116565b6002556040805182815290516000916001600160a01b038516917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35050565b6000610ede83836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f770000815250610ded565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106111545782800160ff19823516178555611181565b82800160010185558215611181579182015b82811115611181578235825591602001919060010190611166565b5061118d929150611191565b5090565b61067091905b8082111561118d576000815560010161119756fe45524332303a207472616e7366657220746f20746865207a65726f2061646472657373456e65726769546f6b656e3a20726564656d7074696f6e20616d6f756e7420746f6f20736d616c6c45524332303a206275726e20616d6f756e7420657863656564732062616c616e636545524332303a20617070726f766520746f20746865207a65726f206164647265737345524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e6365456e65726769546f6b656e3a20464f5242494444454e0000000000000000000045524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636545524332303a206275726e2066726f6d20746865207a65726f206164647265737345524332303a207472616e736665722066726f6d20746865207a65726f206164647265737345524332303a20617070726f76652066726f6d20746865207a65726f206164647265737345524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726fa265627a7a72315820d37f6bb343596132fc6906caf5d652c12234e5f957a3875d194be046a59fea3164736f6c63430005110032
[ 38 ]
0x63A995cfB3Badabe007263917024369529BaF26f
pragma solidity 0.5.15; library Addresses { function isContract(address account) internal view returns (bool) { uint256 size; // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } function performEthTransfer(address recipient, uint256 amount) internal { // solium-disable-next-line security/no-call-value (bool success, ) = recipient.call.value(amount)(""); // NOLINT: low-level-calls. require(success, "ETH_TRANSFER_FAILED"); } /* Safe wrapper around ERC20/ERC721 calls. This is required because many deployed ERC20 contracts don't return a value. See https://github.com/ethereum/solidity/issues/4116. */ function safeTokenContractCall(address tokenAddress, bytes memory callData) internal { require(isContract(tokenAddress), "BAD_TOKEN_ADDRESS"); // solium-disable-next-line security/no-low-level-calls // NOLINTNEXTLINE: low-level-calls. (bool success, bytes memory returndata) = address(tokenAddress).call(callData); require(success, string(returndata)); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "TOKEN_OPERATION_FAILED"); } } } library StarkExTypes { // Structure representing a list of verifiers (validity/availability). // A statement is valid only if all the verifiers in the list agree on it. // Adding a verifier to the list is immediate - this is used for fast resolution of // any soundness issues. // Removing from the list is time-locked, to ensure that any user of the system // not content with the announced removal has ample time to leave the system before it is // removed. struct ApprovalChainData { address[] list; // Represents the time after which the verifier with the given address can be removed. // Removal of the verifier with address A is allowed only in the case the value // of unlockedForRemovalTime[A] != 0 and unlockedForRemovalTime[A] < (current time). mapping (address => uint256) unlockedForRemovalTime; } } contract GovernanceStorage { struct GovernanceInfoStruct { mapping (address => bool) effectiveGovernors; address candidateGovernor; bool initialized; } // A map from a Governor tag to its own GovernanceInfoStruct. mapping (string => GovernanceInfoStruct) internal governanceInfo; } contract IDispatcher { function getSubContract(bytes4 selector) internal view returns (address); function setSubContractAddress(uint256 index, address subContract) internal; function getNumSubcontracts() internal pure returns (uint256); function validateSubContractIndex(uint256 index, address subContract) internal pure; /* Ensures initializer can be called. Reverts otherwise. */ function initializationSentinel() internal view; } contract IFactRegistry { /* Returns true if the given fact was previously registered in the contract. */ function isValid(bytes32 fact) external view returns(bool); } contract Identity { /* Allows a caller, typically another contract, to ensure that the provided address is of the expected type and version. */ function identify() external pure returns(string memory); } contract MainDispatcher is IDispatcher { using Addresses for address; function() external payable { address subContractAddress = getSubContract(msg.sig); require(subContractAddress != address(0x0), "NO_CONTRACT_FOR_FUNCTION"); // solium-disable-next-line security/no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize) // Call the implementation. // out and outsize are 0 for now, as we don"t know the out size yet. let result := delegatecall(gas, subContractAddress, 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) } } } /* 1. Extract subcontracts. 2. Verify correct sub-contract initializer size. 3. Extract sub-contract initializer data. 4. Call sub-contract initializer. The init data bytes passed to initialize are structed as following: I. N slots (uin256 size) addresses of the deployed sub-contracts. II. An address of an external initialization contract (optional, or ZERO_ADDRESS). III. (Up to) N bytes sections of the sub-contracts initializers. If already initialized (i.e. upgrade) we expect the init data to be consistent with this. and if a different size of init data is expected when upgrading, the initializerSize should reflect this. If an external initializer contract is not used, ZERO_ADDRESS is passed in its slot. If the external initializer contract is used, all the remaining init data is passed to it, and internal initialization will not occur. External Initialization Contract -------------------------------- External Initialization Contract (EIC) is a hook for custom initialization. Typically in an upgrade flow, the expected initialization contains only the addresses of the sub-contracts. Normal initialization of the sub-contracts is such that is not needed in an upgrade, and actually may be very dangerous, as changing of state on a working system may corrupt it. In the event that some state initialization is required, the EIC is a hook that allows this. It may be deployed and called specifically for this purpose. The address of the EIC must be provided (if at all) when a new implementation is added to a Proxy contract (as part of the initialization vector). Hence, it is considered part of the code open to reviewers prior to a time-locked upgrade. When a custom initialization is performed using an EIC, the main dispatcher initialize extracts and stores the sub-contracts addresses, and then yields to the EIC, skipping the rest of its initialization code. Flow of MainDispatcher initialize --------------------------------- 1. Extraction and assignment of subcontracts addresses Main dispatcher expects a valid and consistent set of addresses in the passed data. It validates that, extracts the addresses from the data, and validates that the addresses are of the expected type and order. Then those addresses are stored. 2. Extraction of EIC address The address of the EIC is extracted from the data. External Initializer Contract is optional. ZERO_ADDRESS indicates it is not used. 3a. EIC is used Dispatcher calls the EIC initialize function with the remaining data. Note - In this option 3b is not performed. 3b. EIC is not used If there is additional initialization data then: I. Sentitenl function is called to permit subcontracts initialization. II. Dispatcher loops through the subcontracts and for each one it extracts the initializing data and passes it to the subcontract's initialize function. */ // NOLINTNEXTLINE: external-function. function initialize(bytes memory data) public { // Number of sub-contracts. uint256 nSubContracts = getNumSubcontracts(); // We support currently 4 bits per contract, i.e. 16, reserving 00 leads to 15. require(nSubContracts <= 15, "TOO_MANY_SUB_CONTRACTS"); // Init data MUST include addresses for all sub-contracts. require(data.length >= 32 * (nSubContracts + 1), "SUB_CONTRACTS_NOT_PROVIDED"); // Size of passed data, excluding sub-contract addresses. uint256 additionalDataSize = data.length - 32 * (nSubContracts + 1); // Sum of subcontract initializers. Aggregated for verification near the end. uint256 totalInitSizes = 0; // Offset (within data) of sub-contract initializer vector. // Just past the sub-contract addresses. uint256 initDataContractsOffset = 32 * (nSubContracts + 1); // 1. Extract & update contract addresses. for (uint256 nContract = 1; nContract <= nSubContracts; nContract++) { address contractAddress; // Extract sub-contract address. // solium-disable-next-line security/no-inline-assembly assembly { contractAddress := mload(add(data, mul(32, nContract))) } validateSubContractIndex(nContract, contractAddress); // Contracts are indexed from 1 and 0 is not in use here. setSubContractAddress(nContract, contractAddress); } // Check if we have an external initializer contract. address externalInitializerAddr; // 2. Extract sub-contract address, again. It's cheaper than reading from storage. // solium-disable-next-line security/no-inline-assembly assembly { externalInitializerAddr := mload(add(data, mul(32, add(nSubContracts, 1)))) } // 3(a). Yield to EIC initialization. if (externalInitializerAddr != address(0x0)) { callExternalInitializer(data, externalInitializerAddr, additionalDataSize); return; } // 3(b). Subcontracts initialization. // I. If no init data passed besides sub-contracts, return. if (additionalDataSize == 0) { return; } // Just to be on the safe side. assert(externalInitializerAddr == address(0x0)); // II. Gate further initialization. initializationSentinel(); // III. Loops through the subcontracts, extracts their data and calls their initializer. for (uint256 nContract = 1; nContract <= nSubContracts; nContract++) { address contractAddress; // Extract sub-contract address, again. It's cheaper than reading from storage. // solium-disable-next-line security/no-inline-assembly assembly { contractAddress := mload(add(data, mul(32, nContract))) } // The initializerSize returns the expected size, with respect also to the state status. // i.e. different size if it's a first init (clean state) or upgrade init (alive state). // NOLINTNEXTLINE: calls-loop. // The initializerSize is called via delegatecall, so that it can relate to the state, // and not only to the new contract code. (e.g. return 0 if state-intialized else 192). // solium-disable-next-line security/no-low-level-calls // NOLINTNEXTLINE: reentrancy-events low-level-calls calls-loop. (bool success, bytes memory returndata) = contractAddress.delegatecall( abi.encodeWithSelector(SubContractor(contractAddress).initializerSize.selector)); require(success, string(returndata)); uint256 initSize = abi.decode(returndata, (uint256)); require(initSize <= additionalDataSize, "INVALID_INITIALIZER_SIZE"); require(totalInitSizes + initSize <= additionalDataSize, "INVALID_INITIALIZER_SIZE"); if (initSize == 0) { continue; } // Extract sub-contract init vector. bytes memory subContractInitData = new bytes(initSize); for (uint256 trgOffset = 32; trgOffset <= initSize; trgOffset += 32) { // solium-disable-next-line security/no-inline-assembly assembly { mstore( add(subContractInitData, trgOffset), mload(add(add(data, trgOffset), initDataContractsOffset)) ) } } // Call sub-contract initializer. // solium-disable-next-line security/no-low-level-calls // NOLINTNEXTLINE: low-level-calls. (success, returndata) = contractAddress.delegatecall( abi.encodeWithSelector(this.initialize.selector, subContractInitData) ); require(success, string(returndata)); totalInitSizes += initSize; initDataContractsOffset += initSize; } require( additionalDataSize == totalInitSizes, "MISMATCHING_INIT_DATA_SIZE"); } function callExternalInitializer( bytes memory data, address externalInitializerAddr, uint256 dataSize) private { require(externalInitializerAddr.isContract(), "NOT_A_CONTRACT"); require(dataSize <= data.length, "INVALID_DATA_SIZE"); bytes memory extInitData = new bytes(dataSize); // Prepare memcpy pointers. uint256 srcDataOffset = 32 + data.length - dataSize; uint256 srcData; uint256 trgData; // solium-disable-next-line security/no-inline-assembly assembly { srcData := add(data, srcDataOffset) trgData := add(extInitData, 32) } // Copy initializer data to be passed to the EIC. for (uint256 seek = 0; seek < dataSize; seek += 32) { // solium-disable-next-line security/no-inline-assembly assembly { mstore( add(trgData, seek), mload(add(srcData, seek)) ) } } // solium-disable-next-line security/no-low-level-calls // NOLINTNEXTLINE: low-level-calls. (bool success, bytes memory returndata) = externalInitializerAddr.delegatecall( abi.encodeWithSelector(this.initialize.selector, extInitData) ); require(success, string(returndata)); require(returndata.length == 0, string(returndata)); } } contract ProxyStorage is GovernanceStorage { // Stores the hash of the initialization vector of the added implementation. // Upon upgradeTo the implementation, the initialization vector is verified // to be identical to the one submitted when adding the implementation. mapping (address => bytes32) internal initializationHash; // The time after which we can switch to the implementation. mapping (address => uint256) internal enabledTime; // A central storage of the flags whether implementation has been initialized. // Note - it can be used flexibly enough to accommodate multiple levels of initialization // (i.e. using different key salting schemes for different initialization levels). mapping (bytes32 => bool) internal initialized; } contract SubContractor is Identity { function initialize(bytes calldata data) external; function initializerSize() external view returns(uint256); } contract MainStorage is ProxyStorage { IFactRegistry escapeVerifier_; // Global dex-frozen flag. bool stateFrozen; // NOLINT: constable-states. // Time when unFreeze can be successfully called (UNFREEZE_DELAY after freeze). uint256 unFreezeTime; // NOLINT: constable-states. // Pending deposits. // A map STARK key => asset id => vault id => quantized amount. mapping (uint256 => mapping (uint256 => mapping (uint256 => uint256))) pendingDeposits; // Cancellation requests. // A map STARK key => asset id => vault id => request timestamp. mapping (uint256 => mapping (uint256 => mapping (uint256 => uint256))) cancellationRequests; // Pending withdrawals. // A map STARK key => asset id => quantized amount. mapping (uint256 => mapping (uint256 => uint256)) pendingWithdrawals; // vault_id => escape used boolean. mapping (uint256 => bool) escapesUsed; // Number of escapes that were performed when frozen. uint256 escapesUsedCount; // NOLINT: constable-states. // Full withdrawal requests: stark key => vaultId => requestTime. // stark key => vaultId => requestTime. mapping (uint256 => mapping (uint256 => uint256)) fullWithdrawalRequests; // State sequence number. uint256 sequenceNumber; // NOLINT: constable-states uninitialized-state. // Vaults Tree Root & Height. uint256 vaultRoot; // NOLINT: constable-states uninitialized-state. uint256 vaultTreeHeight; // NOLINT: constable-states uninitialized-state. // Order Tree Root & Height. uint256 orderRoot; // NOLINT: constable-states uninitialized-state. uint256 orderTreeHeight; // NOLINT: constable-states uninitialized-state. // True if and only if the address is allowed to add tokens. mapping (address => bool) tokenAdmins; // True if and only if the address is allowed to register users. mapping (address => bool) userAdmins; // True if and only if the address is an operator (allowed to update state). mapping (address => bool) operators; // Mapping of contract ID to asset data. mapping (uint256 => bytes) assetTypeToAssetInfo; // NOLINT: uninitialized-state. // Mapping of registered contract IDs. mapping (uint256 => bool) registeredAssetType; // NOLINT: uninitialized-state. // Mapping from contract ID to quantum. mapping (uint256 => uint256) assetTypeToQuantum; // NOLINT: uninitialized-state. // This mapping is no longer in use, remains for backwards compatibility. mapping (address => uint256) starkKeys_DEPRECATED; // NOLINT: naming-convention. // Mapping from STARK public key to the Ethereum public key of its owner. mapping (uint256 => address) ethKeys; // NOLINT: uninitialized-state. // Timelocked state transition and availability verification chain. StarkExTypes.ApprovalChainData verifiersChain; StarkExTypes.ApprovalChainData availabilityVerifiersChain; // Batch id of last accepted proof. uint256 lastBatchId; // NOLINT: constable-states uninitialized-state. // Mapping between sub-contract index to sub-contract address. mapping(uint256 => address) subContracts; // NOLINT: uninitialized-state. } contract StarkExchange is MainStorage, MainDispatcher { string public constant VERSION = "2.0.1"; string constant INIT_TAG = "INIT_TAG_Starkware.StarkExchange.2020.2.0.1"; uint256 constant SUBCONTRACT_BITS = 4; // Salt for a 7 bit unique spread of all relevant selectors. Pre-calculated. // ---------- The following code was auto-generated. PLEASE DO NOT EDIT. ---------- uint256 constant MAGIC_SALT = 45733; uint256 constant IDX_MAP_0 = 0x201220230201001000221220210222000000020303010211120120200003002; uint256 constant IDX_MAP_1 = 0x2100003000200010003000000300100220220203000020000101022100011100; // ---------- End of auto-generated code. ---------- function validateSubContractIndex(uint256 index, address subContract) internal pure{ string memory id = SubContractor(subContract).identify(); bytes32 hashed_expected_id = keccak256(abi.encodePacked(expectedIdByIndex(index))); require( hashed_expected_id == keccak256(abi.encodePacked(id)), "MISPLACED_INDEX_OR_BAD_CONTRACT_ID"); } function expectedIdByIndex(uint256 index) private pure returns (string memory id) { if (index == 1){ id = "StarkWare_AllVerifiers_2020_1"; } else if (index == 2){ id = "StarkWare_TokensAndRamping_2020_1"; } else if (index == 3){ id = "StarkWare_StarkExState_2020_1"; } else { revert("UNEXPECTED_INDEX"); } } function getNumSubcontracts() internal pure returns (uint256) { return 3; } function getSubContract(bytes4 selector) internal view returns (address) { uint256 location = 0x7F & uint256(keccak256(abi.encodePacked(selector, MAGIC_SALT))); uint256 subContractIdx; uint256 offset = SUBCONTRACT_BITS * location % 256; if (location < 64) { subContractIdx = (IDX_MAP_0 >> offset) & 0xF; } else { subContractIdx = (IDX_MAP_1 >> offset) & 0xF; } return subContracts[subContractIdx]; } function setSubContractAddress(uint256 index, address subContractAddress) internal { subContracts[index] = subContractAddress; } function initializationSentinel() internal view { string memory REVERT_MSG = "INITIALIZATION_BLOCKED"; // This initializer sets roots etc. It must not be applied twice. // I.e. it can run only when the state is still empty. require(vaultRoot == 0, REVERT_MSG); require(vaultTreeHeight == 0, REVERT_MSG); require(orderRoot == 0, REVERT_MSG); require(orderTreeHeight == 0, REVERT_MSG); } }
0x6080604052600436106100295760003560e01c8063439fab91146100bc578063ffa1ad741461016f575b60006100406000356001600160e01b0319166101f9565b90506001600160a01b038116610098576040805162461bcd60e51b81526020600482015260186024820152772727afa1a7a72a2920a1aa2fa327a92fa32aa721aa24a7a760411b604482015290519081900360640190fd5b3660008037600080366000845af43d6000803e8080156100b7573d6000f35b3d6000fd5b3480156100c857600080fd5b5061016d600480360360208110156100df57600080fd5b810190602081018135600160201b8111156100f957600080fd5b82018360208201111561010b57600080fd5b803590602001918460018302840111600160201b8311171561012c57600080fd5b91908080601f0160208091040260200160405190810160405280939291908181526020018383808284376000920191909152509295506102c7945050505050565b005b34801561017b57600080fd5b506101846108a7565b6040805160208082528351818301528351919283929083019185019080838360005b838110156101be5781810151838201526020016101a6565b50505050905090810190601f1680156101eb5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b604080516001600160e01b0319831660208083019190915261b2a56024808401919091528351808403909101815260449092019092528051910120600090607f16818061010060048402069050604083101561027c57600f7f0201220230201001000221220210222000000020303010211120120200003002821c1691506102a5565b600f7f2100003000200010003000000300100220220203000020000101022100011100821c1691505b506000908152601e60205260409020546001600160a01b03169150505b919050565b60006102d16108c8565b9050600f811115610322576040805162461bcd60e51b8152602060048201526016602482015275544f4f5f4d414e595f5355425f434f4e54524143545360501b604482015290519081900360640190fd5b806001016020028251101561037e576040805162461bcd60e51b815260206004820152601a60248201527f5355425f434f4e5452414354535f4e4f545f50524f5649444544000000000000604482015290519081900360640190fd5b8151600182810160200291829003916000915b8481116103bc57602081028601516103a982826108cd565b6103b38282610b20565b50600101610391565b50602060018501028501516001600160a01b038116156103eb576103e1868286610b4e565b50505050506108a4565b836103fa5750505050506108a4565b6001600160a01b0381161561040b57fe5b610413610e46565b60015b858111610849576020808202880151604080516004815260248101825292830180516001600160e01b0316633cc660ad60e01b1781529051835192936000936060936001600160a01b03871693918291908083835b6020831061048a5780518252601f19909201916020918201910161046b565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146104ea576040519150601f19603f3d011682016040523d82523d6000602084013e6104ef565b606091505b509150915081819061057f5760405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561054457818101518382015260200161052c565b50505050905090810190601f1680156105715780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600081806020019051602081101561059757600080fd5b50519050888111156105eb576040805162461bcd60e51b8152602060048201526018602482015277494e56414c49445f494e495449414c495a45525f53495a4560401b604482015290519081900360640190fd5b88818901111561063d576040805162461bcd60e51b8152602060048201526018602482015277494e56414c49445f494e495449414c495a45525f53495a4560401b604482015290519081900360640190fd5b8061064b5750505050610841565b6060816040519080825280601f01601f191660200182016040528015610678576020820181803883390190505b50905060205b828111610697578c81018901518282015260200161067e565b506040516020602482018181528351604484015283516001600160a01b0389169363439fab9160e01b9386939283926064019185019080838360005b838110156106eb5781810151838201526020016106d3565b50505050905090810190601f1680156107185780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529181526020820180516001600160e01b03166001600160e01b0319909716969096178652518151919590945084935091508083835b6020831061077a5780518252601f19909201916020918201910161075b565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146107da576040519150601f19603f3d011682016040523d82523d6000602084013e6107df565b606091505b50909450925082846108325760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561054457818101518382015260200161052c565b50509687019695909501945050505b600101610416565b5082841461089e576040805162461bcd60e51b815260206004820152601a60248201527f4d49534d41544348494e475f494e49545f444154415f53495a45000000000000604482015290519081900360640190fd5b50505050505b50565b60405180604001604052806005815260200164322e302e3160d81b81525081565b600390565b6060816001600160a01b031663eeb728666040518163ffffffff1660e01b815260040160006040518083038186803b15801561090857600080fd5b505afa15801561091c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561094557600080fd5b8101908080516040519392919084600160201b82111561096457600080fd5b90830190602082018581111561097957600080fd5b8251600160201b81118282018810171561099257600080fd5b82525081516020918201929091019080838360005b838110156109bf5781810151838201526020016109a7565b50505050905090810190601f1680156109ec5780820380516001836020036101000a031916815260200191505b5060405250505090506000610a0084610fbe565b6040516020018082805190602001908083835b60208310610a325780518252601f199092019160209182019101610a13565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052805190602001209050816040516020018082805190602001908083835b60208310610aa25780518252601f199092019160209182019101610a83565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051602081830303815290604052805190602001208114610b1a5760405162461bcd60e51b81526004018080602001828103825260228152602001806110b66022913960400191505060405180910390fd5b50505050565b6000918252601e602052604090912080546001600160a01b0319166001600160a01b03909216919091179055565b610b60826001600160a01b03166110af565b610ba2576040805162461bcd60e51b815260206004820152600e60248201526d1393d517d057d0d3d395149050d560921b604482015290519081900360640190fd5b8251811115610bec576040805162461bcd60e51b8152602060048201526011602482015270494e56414c49445f444154415f53495a4560781b604482015290519081900360640190fd5b6060816040519080825280601f01601f191660200182016040528015610c19576020820181803883390190505b5084519091508290036020818101918601810190830160005b85811015610c4a578281015182820152602001610c32565b5060006060876001600160a01b031663439fab9160e01b876040516024018080602001828103825283818151815260200191508051906020019080838360005b83811015610ca2578181015183820152602001610c8a565b50505050905090810190601f168015610ccf5780820380516001836020036101000a031916815260200191505b5060408051601f198184030181529181526020820180516001600160e01b03166001600160e01b0319909716969096178652518151919590945084935091508083835b60208310610d315780518252601f199092019160209182019101610d12565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d8060008114610d91576040519150601f19603f3d011682016040523d82523d6000602084013e610d96565b606091505b5091509150818190610de95760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561054457818101518382015260200161052c565b508051819015610e3a5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561054457818101518382015260200161052c565b50505050505050505050565b60408051808201909152601681527512539255125053125690551253d397d09313d0d2d15160521b6020820152600d54819015610ec45760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561054457818101518382015260200161052c565b50600e54819015610f165760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561054457818101518382015260200161052c565b50600f54819015610f685760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561054457818101518382015260200161052c565b50601054819015610fba5760405162461bcd60e51b815260206004820181815283516024840152835190928392604490910191908501908083836000831561054457818101518382015260200161052c565b5050565b60608160011415611003575060408051808201909152601d81527f537461726b576172655f416c6c5665726966696572735f323032305f3100000060208201526102c2565b816002141561102c576040518060600160405280602181526020016110d86021913990506102c2565b816003141561106f575060408051808201909152601d81527f537461726b576172655f537461726b457853746174655f323032305f3100000060208201526102c2565b6040805162461bcd60e51b815260206004820152601060248201526f0aa9c8ab0a08a86a88a88be929c888ab60831b604482015290519081900360640190fd5b3b15159056fe4d4953504c414345445f494e4445585f4f525f4241445f434f4e54524143545f4944537461726b576172655f546f6b656e73416e6452616d70696e675f323032305f31a265627a7a723158205197bcf9f481f35f2068065d7d3daf11cf72da62745f8734a36cbe3dba01ae0564736f6c634300050f0032
[ 0 ]
0x6403BD92589F825FfeF6b62177FCe9149947cb9f
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 990000000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint256 pow10 = 10 ** (18 - _getDecimals(_collateralAddress)); // fetch all needed data (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance * pow10, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLTV, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLTV); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return wdiv(totalCollateralETH, collateralPrice) / pow10; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLTV, totalCollateralETH), wmul(tokenLTV, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLTV)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLTV) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice) / pow10, NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))), NINETY_NINE_PERCENT_WEI); } function getMaxBoost(address _borrowAddress, address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLTV,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLTV,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); totalCollateralETH = div(mul(totalCollateralETH, currentLTV), 100); uint256 availableBorrowsETH = wmul(mul(div(sub(totalCollateralETH, totalBorrowsETH), sub(100, tokenLTV)), 100), NINETY_NINE_PERCENT_WEI); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wdiv(availableBorrowsETH, borrowPrice) / (10 ** (18 - _getDecimals(_borrowAddress))); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wdiv(_gasCost, price) / (10 ** (18 - _getDecimals(_tokenAddr))); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost for transaction /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return gasCost The amount we took for the gas cost function getGasCost(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint gasCost) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); gasCost = _gasCost; } // fee can't go over 20% of the whole amount if (gasCost > (_amount / 5)) { gasCost = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(gasCost); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, gasCost); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_amount == 0) return; if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } function _getDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return ERC20(_token).decimals(); } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); if (totalBorrowsETH == 0) return uint256(0); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } function proxyOwner() internal returns(address) { return DSAuth(address(this)).owner(); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract CreamSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Eth if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEther) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToEther, cTokenBalance, sumCollateral); } // Sum up debt in Eth if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CreamSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; address public constant COMPTROLLER = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the cream position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); _gasCost = wdiv(_gasCost, ethTokenPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); feeAmount = wdiv(_gasCost, ethTokenPrice); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInEth == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); if (_cCollAddress == CETH_ADDRESS) { if (liquidityInEth > usersBalance) return usersBalance; return sub(liquidityInEth, (liquidityInEth / 100)); } uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); if (liquidityInToken > usersBalance) return usersBalance; return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); if (_cBorrowAddress == CETH_ADDRESS) return sub(liquidityInEth, (liquidityInEth / 100)); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInEth, ethPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CreamBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } contract DFSExchangeData { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct OffchainData { address exchangeAddr; address allowanceTarget; uint256 price; uint256 protocolFee; bytes callData; } struct ExchangeData { address srcAddr; address destAddr; uint256 srcAmount; uint256 destAmount; uint256 minPrice; uint256 dfsFeeDivider; address user; address wrapper; bytes wrapperData; OffchainData offchainData; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { return abi.encode(_exData); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { _exData = abi.decode(_data, (ExchangeData)); } } contract DFSExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ZRX_ALLOWLIST_ADDR = 0x4BA1f38427b33B8ab7Bb0490200dAE1F1C36823F; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _user Address of the user /// @param _token Address of the token /// @param _dfsFeeDivider Dfs fee divider /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _user, address _token, uint256 _dfsFeeDivider) internal returns (uint256 feeAmount) { if (_dfsFeeDivider != 0 && Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_user)) { _dfsFeeDivider = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_user); } if (_dfsFeeDivider == 0) { feeAmount = 0; } else { feeAmount = _amount / _dfsFeeDivider; // fee can't go over 10% of the whole amount if (feeAmount > (_amount / 10)) { feeAmount = _amount / 10; } if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract DFSPricesV3 is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers, bytes[] memory _additionalData ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type, _additionalData[i]); } return getBiggestRate(_wrappers, rates); } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type, bytes memory _additionalData ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256,bytes)", _srcToken, _destToken, _amount, _additionalData )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { struct CompMarketState { uint224 index; uint32 block; } function claimComp(address holder) public virtual; function claimComp(address holder, address[] memory cTokens) public virtual; function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual; function compSupplyState(address) public view virtual returns (CompMarketState memory); function compSupplierIndex(address,address) public view virtual returns (uint); function compAccrued(address) public view virtual returns (uint); function compBorrowState(address) public view virtual returns (CompMarketState memory); function compBorrowerIndex(address,address) public view virtual returns (uint); function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } interface ExchangeInterfaceV3 { function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external view returns (uint); } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; function balanceOf(address _owner) external virtual view returns (uint256 balance); } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscriptions { function unsubscribe() external virtual ; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentStableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public virtual returns (uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, 0); GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { using SafeERC20 for ERC20; address payable public constant MCD_CREATE_FLASH_LOAN = 0x78aF7A2Ee6C2240c748aDdc42aBc9A693559dcaF; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (!isEthJoinAddr(_createData.joinAddr)) { ERC20(getCollateralAddr(_createData.joinAddr)).safeTransferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).safeTransfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract BotRegistry is AdminAuth { mapping (address => bool) public botList; constructor() public { botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true; botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true; botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true; botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true; botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true; } function setBot(address _botAddr, bool _state) public onlyOwner { botList[_botAddr] = _state; } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } 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) { // 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) { 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; mapping(address => bool) private nonPayableAddrs; constructor() public { zrxAllowlist[0x6958F5e95332D93D21af0D7B9Ca85B8212fEE0A5] = true; zrxAllowlist[0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef] = true; zrxAllowlist[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true; zrxAllowlist[0x080bf510FCbF18b91105470639e9561022937712] = true; nonPayableAddrs[0x080bf510FCbF18b91105470639e9561022937712] = true; } function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } function addNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = true; } function removeNonPayableAddr(address _nonPayableAddr) public onlyOwner { nonPayableAddrs[_nonPayableAddr] = false; } function isNonPayableAddr(address _addr) public view returns(bool) { return nonPayableAddrs[_addr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount + originationFee; } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); if (originationFee > 0) { ERC20(_tokenAddr).safeTransfer(_onBehalf, originationFee); } approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 borrowRateStable; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 liquidationRatio; uint256 price; bool usageAsCollateralEnabled; } struct UserToken { address token; uint256 balance; uint256 borrows; uint256 borrowRateMode; bool enabledAsCollateral; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (UserToken[] memory userTokens) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); userTokens = new UserToken[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; userTokens[i].token = asset; (userTokens[i].balance, userTokens[i].borrows,,userTokens[i].borrowRateMode,,,,,,userTokens[i].enabledAsCollateral) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (uint256 ltv, uint256 liqRatio,,, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowingEnabled,) = ILendingPool(lendingPoolAddress).getReserveConfigurationData(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: borrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]) : 0, borrowRateStable: stableBorrowingEnabled ? ILendingPool(lendingPoolCoreAddress).getReserveCurrentStableBorrowRate(_tokenAddresses[i]) : 0, totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, liquidationRatio: liqRatio, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price) * (10 ** (18 - _getDecimals(reserve))); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x29F4af15ad64C509c4140324cFE71FB728D10d2B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user)); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x11c937fD367D75465DC211c367684d8d4520E6f9; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 20; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompBalance is Exponential, GasBurner { ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); address public constant COMP_ADDR = 0xc00e94Cb662C3520282E6f5717214004A7f26888; uint224 public constant compInitialIndex = 1e36; function claimComp(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) public burnGas(8) { _claim(_user, _cTokensSupply, _cTokensBorrow); ERC20(COMP_ADDR).transfer(msg.sender, ERC20(COMP_ADDR).balanceOf(address(this))); } function _claim(address _user, address[] memory _cTokensSupply, address[] memory _cTokensBorrow) internal { address[] memory u = new address[](1); u[0] = _user; comp.claimComp(u, _cTokensSupply, false, true); comp.claimComp(u, _cTokensBorrow, true, false); } function getBalance(address _user, address[] memory _cTokens) public view returns (uint) { uint compBalance = 0; for(uint i = 0; i < _cTokens.length; ++i) { compBalance += getSuppyBalance(_cTokens[i], _user); compBalance += getBorrowBalance(_cTokens[i], _user); } compBalance += ERC20(COMP_ADDR).balanceOf(_user); return compBalance; } function getSuppyBalance(address _cToken, address _supplier) public view returns (uint supplierAccrued) { ComptrollerInterface.CompMarketState memory supplyState = comp.compSupplyState(_cToken); Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: comp.compSupplierIndex(_cToken, _supplier)}); if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = compInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = CTokenInterface(_cToken).balanceOf(_supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); supplierAccrued = add_(comp.compAccrued(_supplier), supplierDelta); } function getBorrowBalance(address _cToken, address _borrower) public view returns (uint borrowerAccrued) { ComptrollerInterface.CompMarketState memory borrowState = comp.compBorrowState(_cToken); Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: comp.compBorrowerIndex(_cToken, _borrower)}); Exp memory marketBorrowIndex = Exp({mantissa: CTokenInterface(_cToken).borrowIndex()}); if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(CTokenInterface(_cToken).borrowBalanceStored(_borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); borrowerAccrued = add_(comp.compAccrued(_borrower), borrowerDelta); } } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, 0); ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0xaf9f8781A4c39Ce2122019fC05F22e3a662B0A32; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract CreamBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d5BC3c8d13dcB8bF317092d84783c2697AE9258; using SafeERC20 for ERC20; /// @notice User deposits tokens to the cream protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the cream protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the cream protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the cream protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the cream market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the cream market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CreamLoanInfo is CreamSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0xD06527D5e56A3495252A528C4987003b712860eE; /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches cream prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches cream collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in eth if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToEth) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToEth, cTokenBalance); collPos++; } // Sum up debt in eth if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in eth /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a cream user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CreamImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant CREAM_BORROW_PROXY = 0x87F198Ef6116CdBC5f36B581d212ad950b7e2Ddd; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay cream debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(CREAM_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CreamImportTaker is CreamSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant CREAM_IMPORT_FLASH_LOAN = 0x24F4aC0Fe758c45cf8425D8Fbdd608cca9A7dBf8; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve cream_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(CREAM_IMPORT_FLASH_LOAN); lendingPool.flashLoan(CREAM_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(CREAM_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = getProtocolFee(exData.srcAddr, exData.srcAmount); (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isNonPayableAddr(_exData.exchangeAddr)) { _ethAmount = 0; } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } /// @notice Calculates protocol fee /// @param _srcAddr selling token address (if eth should be WETH) /// @param _srcAmount amount we are selling function getProtocolFee(address _srcAddr, uint256 _srcAmount) internal view returns(uint256) { // if we are not selling ETH msg value is always the protocol fee if (_srcAddr != WETH_ADDRESS) return address(this).balance; // if msg value is larger than srcAmount, that means that msg value is protocol fee + srcAmount, so we subsctract srcAmount from msg value // we have an edge case here when protocol fee is higher than selling amount if (address(this).balance > _srcAmount) return address(this).balance - _srcAmount; // if msg value is lower than src amount, that means that srcAmount isn't included in msg value, so we return msg value return address(this).balance; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount)); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(1 ether, wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount)); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(1 ether, wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount)); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DFSExchangeCore is DFSExchangeHelper, DSMath, DFSExchangeData { string public constant ERR_SLIPPAGE_HIT = "Slippage hit"; string public constant ERR_DEST_AMOUNT_MISSING = "Dest amount missing"; string public constant ERR_WRAPPER_INVALID = "Wrapper invalid"; string public constant ERR_OFFCHAIN_DATA_INVALID = "Offchain data invalid"; /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); // Try 0x first and then fallback on specific wrapper if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.SELL); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), ERR_SLIPPAGE_HIT); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, ERR_DEST_AMOUNT_MISSING); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } exData.srcAmount -= getFee(exData.srcAmount, exData.user, exData.srcAddr, exData.dfsFeeDivider); if (exData.offchainData.price > 0) { (success, swapedTokens) = takeOrder(exData, ActionType.BUY); if (success) { wrapper = exData.offchainData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, ERR_SLIPPAGE_HIT); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data function takeOrder( ExchangeData memory _exData, ActionType _type ) private returns (bool success, uint256) { if (_exData.srcAddr != KYBER_ETH_ADDRESS) { ERC20(_exData.srcAddr).safeApprove(_exData.offchainData.allowanceTarget, _exData.srcAmount); } // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.offchainData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.offchainData.callData, 36, _exData.destAmount); } uint256 tokensBefore = getBalance(_exData.destAddr); if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.offchainData.exchangeAddr)) { (success, ) = _exData.offchainData.exchangeAddr.call{value: _exData.offchainData.protocolFee}(_exData.offchainData.callData); } else { success = false; } uint256 tokensSwaped = 0; if (success) { // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr) - tokensBefore; } return (success, tokensSwaped); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), ERR_WRAPPER_INVALID); ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). sell(_exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.wrapperData); } else { swapedTokens = ExchangeInterfaceV3(_exData.wrapper). buy(_exData.srcAddr, _exData.destAddr, _exData.destAmount, _exData.wrapperData); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert(ERR_OFFCHAIN_DATA_INVALID); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint rate) { uint256 srcRate = getSellRate(_destAddr, _srcAddr, _destAmount, _additionalData); uint256 srcAmount = wmul(srcRate, _destAmount); rate = getSellRate(_srcAddr, _destAddr, srcAmount, _additionalData); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(1 ether, wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount)); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapperV3 is DSMath, ExchangeInterfaceV3, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = abi.decode(_additionalData, (address[])); ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount, bytes memory _additionalData) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = abi.decode(_additionalData, (address[])); uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(_destAmount, amounts[0]); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function borrowIndex() public view virtual returns (uint); function borrowBalanceStored(address) public view virtual returns(uint); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 500000000000; // 500 gwei uint public REPAY_GAS_COST = 1800000; uint public BOOST_GAS_COST = 1800000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); modifier onlyApproved() { require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot"); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256,uint256,address)", _exchangeData, _cdpId, gasCost, _joinAddr)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt uint drawnAmount = drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; if (_closeData.toDai) { _exchangeData.srcAmount = drawnAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, _user); } else { dfsFee = getFee(_closeData.daiAmount, _user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (isEthJoinAddr(_joinAddr)) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { ERC20(address(Join(_joinAddr).gem())).safeApprove(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Checks if the join address is one of the Ether coll. types /// @param _joinAddr Join address to check function isEthJoinAddr(address _joinAddr) internal view returns (bool) { // if it's dai_join_addr don't check gem() it will fail if (_joinAddr == 0x9759A6Ac90977b93B58547b4A71c78317f391A28) return false; // if coll is weth it's and eth type coll if (address(Join(_joinAddr).gem()) == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) { return true; } return false; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant MANUAL_SERVICE_FEE = 400; // 0.25% Fee uint public constant AUTOMATIC_SERVICE_FEE = 333; // 0.3% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } ERC20(address(Join(_joinAddr).gem())).safeApprove(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (isEthJoinAddr(_joinAddr)) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(collateral, (div(mul(mat, debt), price))); uint normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); // take one percent due to precision issues return normalizeMaxCollateral * 99 / 100; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0xec504C93A40A557cC85dAc3e908E85A887438079; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); uint maxLiq = getAvailableLiquidity(DAI_JOIN_ADDRESS); if (maxDebt >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxDebt) { _exchangeData.srcAmount = maxDebt; } boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); uint maxLiq = getAvailableLiquidity(_joinAddr); if (maxColl >= _exchangeData.srcAmount || maxLiq == 0) { if (_exchangeData.srcAmount > maxColl) { _exchangeData.srcAmount = maxColl; } repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (isEthJoinAddr(_joinAddr) || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else if (_joinAddr == DAI_JOIN_ADDRESS) { return DAI_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount -= getFee(getBalance(exchangeData.srcAddr), exchangeData.srcAddr, paramData.proxy); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.srcAmount -= getFee(exchangeData.srcAmount, exchangeData.srcAddr, paramData.proxy); exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], _amount, numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxyInterface proxy = DSProxyInterface(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract LoanShifterTaker is AdminAuth, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MCD_SUB_ADDRESS = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant COMPOUND_SUB_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x597C52281b31B9d949a9D8fEbA08F7A2530a965e); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } enum Unsub { NO_UNSUB, FIRST_UNSUB, SECOND_UNSUB, BOTH_UNSUB } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; Unsub unsub; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public payable burnGas(20) { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); logEvent(_exchangeData, _loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.debtAddr1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); loanShifterReceiverAddr.transfer(address(this).balance); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), _loanShift.debtAmount, paramsData); removePermission(loanShifterReceiverAddr); unsubFromAutomation( _loanShift.unsub, _loanShift.id1, _loanShift.id2, _loanShift.fromProtocol, _loanShift.toProtocol ); logEvent(_exchangeData, _loanShift); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function logEvent( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address srcAddr = _exchangeData.srcAddr; address destAddr = _exchangeData.destAddr; uint collAmount = _exchangeData.srcAmount; uint debtAmount = _exchangeData.destAmount; if (_loanShift.swapType == SwapType.NO_SWAP) { srcAddr = _loanShift.addrLoan1; destAddr = _loanShift.debtAddr1; collAmount = _loanShift.collAmount; debtAmount = _loanShift.debtAmount; } DefisaverLogger(DEFISAVER_LOGGER) .Log(address(this), msg.sender, "LoanShifter", abi.encode( _loanShift.fromProtocol, _loanShift.toProtocol, _loanShift.swapType, srcAddr, destAddr, collAmount, debtAmount )); } function unsubFromAutomation(Unsub _unsub, uint _cdp1, uint _cdp2, Protocols _from, Protocols _to) internal { if (_unsub != Unsub.NO_UNSUB) { if (_unsub == Unsub.FIRST_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp1, _from); } if (_unsub == Unsub.SECOND_UNSUB || _unsub == Unsub.BOTH_UNSUB) { unsubscribe(_cdp2, _to); } } } function unsubscribe(uint _cdpId, Protocols _protocol) internal { if (_cdpId != 0 && _protocol == Protocols.MCD) { IMCDSubscriptions(MCD_SUB_ADDRESS).unsubscribe(_cdpId); } if (_protocol == Protocols.COMPOUND) { ICompoundSubscriptions(COMPOUND_SUB_ADDRESS).unsubscribe(); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract CompShifter is CompoundSaverHelper { using SafeERC20 for ERC20; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getLoanAmount(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return getWholeDebt(_cdpId, _joinAddr); } function getWholeDebt(uint _cdpId, address _joinAddr) public returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).safeTransfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).safeTransfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).safeTransfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { using SafeERC20 for ERC20; address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (isEthJoinAddr(_joinAddr)) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.safeTransfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (isEthJoinAddr(_joinAddr)) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (isEthJoinAddr(_joinAddrTo)) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); // uint256 maxCollateral = IAToken(aTokenCollateral).balanceOf(address(this)); // don't swap more than maxCollateral // _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; IAToken(aTokenCollateral).redeem(_data.srcAmount); uint256 destAmount = _data.srcAmount; if (_data.srcAddr != _data.destAddr) { // swap (, destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); } else { destAmount -= getGasCost(destAmount, user, _gasCost, _data.destAddr); } // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,uint256 borrowRateMode,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); // skipping this check as its too expensive // uint256 maxBorrow = getMaxBoost(_data.srcAddr, _data.destAddr, address(this)); // _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, borrowRateMode == 0 ? VARIABLE_RATE : borrowRateMode, AAVE_REFERRAL_CODE); uint256 destAmount; if (_data.destAddr != _data.srcAddr) { _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, destAmount) = _sell(_data); } else { _data.srcAmount -= getGasCost(_data.srcAmount, user, _gasCost, _data.srcAddr); destAmount = _data.srcAmount; } if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, tx.origin, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract AaveSaverReceiver is AaveHelper, AdminAuth, SaverExchangeCore { using SafeERC20 for ERC20; address public constant AAVE_SAVER_PROXY = 0xCab7ce9148499E0dD8228c3c8cDb9B56Ac2bb57a; address public constant AAVE_BASIC_PROXY = 0xd042D4E9B4186c545648c7FfFe87125c976D110B; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( bytes memory exchangeDataBytes, uint256 gasCost, bool isRepay, uint256 ethAmount, uint256 txValue, address user, address proxy ) = abi.decode(data, (bytes,uint256,bool,uint256,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(AAVE_BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); bytes memory functionData = packFunctionCall(exchangeDataBytes, gasCost, isRepay); DSProxy(payable(proxy)).execute{value: txValue}(AAVE_SAVER_PROXY, functionData); // withdraw deposited eth DSProxy(payable(proxy)).execute(AAVE_BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } function packFunctionCall(bytes memory _exchangeDataBytes, uint256 _gasCost, bool _isRepay) internal returns (bytes memory) { ExchangeData memory exData = unpackExchangeData(_exchangeDataBytes); bytes memory functionData; if (_isRepay) { functionData = abi.encodeWithSignature("repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } else { functionData = abi.encodeWithSignature("boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", exData, _gasCost); } return functionData; } /// @dev if contract receive eth, convert it to WETH receive() external override payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveSaverTaker is DydxFlashLoanBase, ProxyPermission, GasBurner, SaverExchangeCore { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_RECEIVER = 0x969DfE84ac318531f13B731c7f21af9918802B94; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; function repay(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, true); } function boost(ExchangeData memory _data, uint256 _gasCost) public payable { _flashLoan(_data, _gasCost, false); } /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction function _flashLoan(ExchangeData memory _data, uint _gasCost, bool _isRepay) internal { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); uint256 ethAmount = ERC20(WETH_ADDR).balanceOf(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, ethAmount, AAVE_RECEIVER); AAVE_RECEIVER.transfer(msg.value); bytes memory encodedData = packExchangeData(_data); operations[1] = _getCallAction( abi.encode(encodedData, _gasCost, _isRepay, ethAmount, msg.value, proxyOwner(), address(this)), AAVE_RECEIVER ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_RECEIVER); solo.operate(accountInfos, operations); removePermission(AAVE_RECEIVER); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompLeverage is SaverExchangeCore, CompBalance, CompoundBasicProxy { address public constant C_COMP_ADDR = 0x70e36f6BF80a52b3B46b3aF8e106CC0ed743E8e4; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Should claim COMP and sell it to the specified token and deposit it back /// @param exchangeData Standard Exchange struct /// @param _cTokensSupply List of cTokens user is supplying /// @param _cTokensBorrow List of cTokens user is borrowing /// @param _cDepositAddr The cToken address of the asset you want to deposit /// @param _inMarket Flag if the cToken is used as collateral function claimAndSell( ExchangeData memory exchangeData, address[] memory _cTokensSupply, address[] memory _cTokensBorrow, address _cDepositAddr, bool _inMarket ) public payable { // Claim COMP token _claim(address(this), _cTokensSupply, _cTokensBorrow); uint compBalance = ERC20(COMP_ADDR).balanceOf(address(this)); uint depositAmount = 0; // Exchange COMP if (exchangeData.srcAddr != address(0)) { exchangeData.srcAmount -= getFee(compBalance, COMP_ADDR, address(this)); (, depositAmount) = _sell(exchangeData); // if we have no deposit after, send back tokens to the user if (_cDepositAddr == address(0)) { ERC20(exchangeData.destAddr).transfer(msg.sender, depositAmount); } } // Deposit back a token if (_cDepositAddr != address(0)) { // if we are just depositing COMP without a swap if (_cDepositAddr == C_COMP_ADDR) { depositAmount = compBalance; } address tokenAddr = getUnderlyingAddr(_cDepositAddr); deposit(tokenAddr, _cDepositAddr, depositAmount, _inMarket); } logger.Log(address(this), msg.sender, "CompLeverage", abi.encode(compBalance, depositAmount, _cDepositAddr, exchangeData.destAmount)); } function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxyInterface proxy = DSProxyInterface(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} struct CompCreateData { address payable proxyAddr; bytes proxyData; address cCollAddr; address cDebtAddr; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address leveragedAsset = _reserve; // If the assets are different if (compCreate.cCollAddr != compCreate.cDebtAddr) { (, uint sellAmount) = _sell(exchangeData); getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr); leveragedAsset = exchangeData.destAddr; } // Send amount to DSProxy sendToProxy(compCreate.proxyAddr, leveragedAsset); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); bytes memory proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); compCreate = CompCreateData({ proxyAddr: payable(proxy), proxyData: proxyData, cCollAddr: cAddresses[0], cDebtAddr: cAddresses[1] }); return (compCreate, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xcEAb38B5C88F33Dabe4D31BDD384E08215526632; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { _exData.srcAmount = collAmount; (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract CreamSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0x1e012554891d271eDc80ba8eB146EA5FF596fA51; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CreamSaverFlashProxy is SaverExchangeCore, CreamSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount _exData.srcAmount = maxColl + _flashLoanData[0]; (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CreamSaverProxy is CreamSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CreamBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract DFSExchange is DFSExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { exData.dfsFeeDivider = SERVICE_FEE; // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ exData.dfsFeeDivider = SERVICE_FEE; // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0xCeB190A35D9D4804b9CE8d0CF79239f6949BfCcB; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); if (loanAmount > availableLiquidity) loanAmount = availableLiquidity; bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } } contract CreamFlashLoanTaker is CreamSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x3ceD2067c0B057611e4E2686Dbe40028962Cc625; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxColl || availableLiquidity == 0) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint availableLiquidity = getAvailableLiquidity(_exData.srcAddr); if (_exData.srcAmount <= maxBorrow || availableLiquidity == 0) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CreamFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } function getAvailableLiquidity(address _tokenAddr) internal view returns (uint liquidity) { if (_tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(_tokenAddr).balanceOf(AAVE_POOL_CORE); } } }
0x6080604052600436106100e15760003560e01c806354123c121161007f578063a7304bf711610059578063a7304bf714610507578063deca5f881461053a578063f851a4401461056d578063f887ea4014610582576100e8565b806354123c121461035d5780635b6f36fc1461042e5780638da5cb5b146104f2576100e8565b80633924db66116100bb5780633924db66146101685780633a1283221461023e57806341c0e1b51461027757806349d666441461028c576100e8565b8063040141e5146100ed5780631e48907b1461011e57806329f7fc9e14610153576100e8565b366100e857005b600080fd5b3480156100f957600080fd5b50610102610597565b604080516001600160a01b039092168252519081900360200190f35b34801561012a57600080fd5b506101516004803603602081101561014157600080fd5b50356001600160a01b03166105af565b005b34801561015f57600080fd5b506101026105e8565b61022c6004803603608081101561017e57600080fd5b6001600160a01b03823581169260208101359091169160408201359190810190608081016060820135600160201b8111156101b857600080fd5b8201836020820111156101ca57600080fd5b803590602001918460018302840111600160201b831117156101eb57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610600945050505050565b60408051918252519081900360200190f35b34801561024a57600080fd5b506101516004803603604081101561026157600080fd5b506001600160a01b038135169060200135610a64565b34801561028357600080fd5b50610151610afd565b34801561029857600080fd5b5061022c600480360360808110156102af57600080fd5b6001600160a01b03823581169260208101359091169160408201359190810190608081016060820135600160201b8111156102e957600080fd5b8201836020820111156102fb57600080fd5b803590602001918460018302840111600160201b8311171561031c57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610b22945050505050565b34801561036957600080fd5b5061022c6004803603608081101561038057600080fd5b6001600160a01b03823581169260208101359091169160408201359190810190608081016060820135600160201b8111156103ba57600080fd5b8201836020820111156103cc57600080fd5b803590602001918460018302840111600160201b831117156103ed57600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610d67945050505050565b61022c6004803603608081101561044457600080fd5b6001600160a01b03823581169260208101359091169160408201359190810190608081016060820135600160201b81111561047e57600080fd5b82018360208201111561049057600080fd5b803590602001918460018302840111600160201b831117156104b157600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250929550610fa4945050505050565b3480156104fe57600080fd5b506101026113e9565b34801561051357600080fd5b506101516004803603602081101561052a57600080fd5b50356001600160a01b03166113f8565b34801561054657600080fd5b506101516004803603602081101561055d57600080fd5b50356001600160a01b0316611431565b34801561057957600080fd5b5061010261145e565b34801561058e57600080fd5b5061010261146d565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b6001546001600160a01b031633146105c657600080fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee81565b600061060b85611485565b945061061684611485565b935060608083806020019051602081101561063057600080fd5b8101908080516040519392919084600160201b82111561064f57600080fd5b90830190602082018581111561066457600080fd5b82518660208202830111600160201b8211171561068057600080fd5b82525081516020918201928201910280838360005b838110156106ad578181015183820152602001610695565b5050505090500160405250505090506106f0737a250d5630b4cf539739df2c5dacb4c659f2488d600019896001600160a01b03166114cd9092919063ffffffff16565b6001600160a01b03861673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc214156108a957737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b0316634a25d94a866000198433426001016040518663ffffffff1660e01b81526004018086815260200185815260200180602001846001600160a01b03168152602001838152602001828103825285818151815260200191508051906020019060200280838360005b838110156107b257818101518382015260200161079a565b505050509050019650505050505050600060405180830381600087803b1580156107db57600080fd5b505af11580156107ef573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561081857600080fd5b8101908080516040519392919084600160201b82111561083757600080fd5b90830190602082018581111561084c57600080fd5b82518660208202830111600160201b8211171561086857600080fd5b82525081516020918201928201910280838360005b8381101561089557818101518382015260200161087d565b505050509050016040525050509150610a39565b737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b0316638803dbee866000198433426001016040518663ffffffff1660e01b81526004018086815260200185815260200180602001846001600160a01b03168152602001838152602001828103825285818151815260200191508051906020019060200280838360005b8381101561094657818101518382015260200161092e565b505050509050019650505050505050600060405180830381600087803b15801561096f57600080fd5b505af1158015610983573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156109ac57600080fd5b8101908080516040519392919084600160201b8211156109cb57600080fd5b9083019060208201858111156109e057600080fd5b82518660208202830111600160201b821117156109fc57600080fd5b82525081516020918201928201910280838360005b83811015610a29578181015183820152602001610a11565b5050505090500160405250505091505b610a4287611579565b81600081518110610a4f57fe5b6020026020010151925050505b949350505050565b6000546001600160a01b03163314610a7b57600080fd5b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b0383161415610adf57600080546040516001600160a01b039091169183156108fc02918491818181858888f19350505050158015610ad9573d6000803e3d6000fd5b50610af9565b600054610af9906001600160a01b0384811691168361165b565b5050565b6000546001600160a01b03163314610b1457600080fd5b6000546001600160a01b0316ff5b6000610b2d85611485565b9450610b3884611485565b93506060828060200190516020811015610b5157600080fd5b8101908080516040519392919084600160201b821115610b7057600080fd5b908301906020820185811115610b8557600080fd5b82518660208202830111600160201b82111715610ba157600080fd5b82525081516020918201928201910280838360005b83811015610bce578181015183820152602001610bb6565b505050509190910160408181526307c0329d60e21b8252600482018b815260248301918252875160448401528751979850606097737a250d5630b4cf539739df2c5dacb4c659f2488d9750631f00ca7496508c95508994509092606401906020808601910280838360005b83811015610c51578181015183820152602001610c39565b50505050905001935050505060006040518083038186803b158015610c7557600080fd5b505afa158015610c89573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015610cb257600080fd5b8101908080516040519392919084600160201b821115610cd157600080fd5b908301906020820185811115610ce657600080fd5b82518660208202830111600160201b82111715610d0257600080fd5b82525081516020918201928201910280838360005b83811015610d2f578181015183820152602001610d17565b505050509050016040525050509050610d5c8582600081518110610d4f57fe5b60200260200101516116ad565b979650505050505050565b6000610d7285611485565b9450610d7d84611485565b93506060828060200190516020811015610d9657600080fd5b8101908080516040519392919084600160201b821115610db557600080fd5b908301906020820185811115610dca57600080fd5b82518660208202830111600160201b82111715610de657600080fd5b82525081516020918201928201910280838360005b83811015610e13578181015183820152602001610dfb565b5050505091909101604081815263d06ca61f60e01b8252600482018b815260248301918252875160448401528751979850606097737a250d5630b4cf539739df2c5dacb4c659f2488d975063d06ca61f96508c95508994509092606401906020808601910280838360005b83811015610e96578181015183820152602001610e7e565b50505050905001935050505060006040518083038186803b158015610eba57600080fd5b505afa158015610ece573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526020811015610ef757600080fd5b8101908080516040519392919084600160201b821115610f1657600080fd5b908301906020820185811115610f2b57600080fd5b82518660208202830111600160201b82111715610f4757600080fd5b82525081516020918201928201910280838360005b83811015610f74578181015183820152602001610f5c565b505050509050016040525050509050610d5c81600183510381518110610f9657fe5b6020026020010151866116ad565b6000610faf85611485565b9450610fba84611485565b9350606080838060200190516020811015610fd457600080fd5b8101908080516040519392919084600160201b821115610ff357600080fd5b90830190602082018581111561100857600080fd5b82518660208202830111600160201b8211171561102457600080fd5b82525081516020918201928201910280838360005b83811015611051578181015183820152602001611039565b505050509050016040525050509050611092737a250d5630b4cf539739df2c5dacb4c659f2488d86896001600160a01b03166114cd9092919063ffffffff16565b6001600160a01b03861673c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2141561124a57737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b03166318cbafe58660018433426001016040518663ffffffff1660e01b81526004018086815260200185815260200180602001846001600160a01b03168152602001838152602001828103825285818151815260200191508051906020019060200280838360005b8381101561115357818101518382015260200161113b565b505050509050019650505050505050600060405180830381600087803b15801561117c57600080fd5b505af1158015611190573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405260208110156111b957600080fd5b8101908080516040519392919084600160201b8211156111d857600080fd5b9083019060208201858111156111ed57600080fd5b82518660208202830111600160201b8211171561120957600080fd5b82525081516020918201928201910280838360005b8381101561123657818101518382015260200161121e565b5050505090500160405250505091506113d9565b737a250d5630b4cf539739df2c5dacb4c659f2488d6001600160a01b03166338ed17398660018433426001016040518663ffffffff1660e01b81526004018086815260200185815260200180602001846001600160a01b03168152602001838152602001828103825285818151815260200191508051906020019060200280838360005b838110156112e65781810151838201526020016112ce565b505050509050019650505050505050600060405180830381600087803b15801561130f57600080fd5b505af1158015611323573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604052602081101561134c57600080fd5b8101908080516040519392919084600160201b82111561136b57600080fd5b90830190602082018581111561138057600080fd5b82518660208202830111600160201b8211171561139c57600080fd5b82525081516020918201928201910280838360005b838110156113c95781810151838201526020016113b1565b5050505090500160405250505091505b81600183510381518110610a4f57fe5b6000546001600160a01b031681565b6001546001600160a01b0316331461140f57600080fd5b600180546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b0316331461144857600080fd5b6001546001600160a01b03161561140f57600080fd5b6001546001600160a01b031681565b737a250d5630b4cf539739df2c5dacb4c659f2488d81565b60006001600160a01b03821673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee146114b157816114c7565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc25b92915050565b604080516001600160a01b038416602482015260006044808301919091528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526115229084906116dd565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663095ea7b360e01b1790526115749084906116dd565b505050565b60405133904780156108fc02916000818181858888f193505050501580156115a5573d6000803e3d6000fd5b506001600160a01b03811673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee146116585761165833826001600160a01b03166370a08231306040518263ffffffff1660e01b815260040180826001600160a01b0316815260200191505060206040518083038186803b15801561161b57600080fd5b505afa15801561162f573d6000803e3d6000fd5b505050506040513d602081101561164557600080fd5b50516001600160a01b038416919061165b565b50565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b1790526115749084906116dd565b6000816116ce6116c585670de0b6b3a764000061178e565b600285046117b2565b816116d557fe5b049392505050565b6060611732826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166117c29092919063ffffffff16565b8051909150156115745780806020019051602081101561175157600080fd5b50516115745760405162461bcd60e51b815260040180806020018281038252602a8152602001806119b1602a913960400191505060405180910390fd5b60008115806117a9575050808202828282816117a657fe5b04145b6114c757600080fd5b808201828110156114c757600080fd5b6060610a5c848460008560606117d785611977565b611828576040805162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015290519081900360640190fd5b60006060866001600160a01b031685876040518082805190602001908083835b602083106118675780518252601f199092019160209182019101611848565b6001836020036101000a03801982511681845116808217855250505050505090500191505060006040518083038185875af1925050503d80600081146118c9576040519150601f19603f3d011682016040523d82523d6000602084013e6118ce565b606091505b509150915081156118e2579150610a5c9050565b8051156118f25780518082602001fd5b8360405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561193c578181015183820152602001611924565b50505050905090810190601f1680156119695780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b6000813f7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470818114801590610a5c57505015159291505056fe5361666545524332303a204552433230206f7065726174696f6e20646964206e6f742073756363656564a2646970667358221220fea8e4383b4dc354c0c720559c81301ec791603d710d3ef0c1688eef14dcc86f64736f6c634300060c0033
[ 21, 4, 37, 17, 11, 8, 9, 12, 16, 5, 2 ]
0x6413fbb36c4990fdaebf3c315b2f5140c828707f
pragma solidity 0.7.0; interface IOwnershipTransferrable { function transferOwnership(address owner) external; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); } abstract contract Ownable is IOwnershipTransferrable { address private _owner; constructor(address owner) { _owner = owner; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } function transferOwnership(address newOwner) override external onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } abstract contract ReentrancyGuard { bool private _entered; modifier noReentrancy() { require(!_entered); _entered = true; _; _entered = false; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); 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); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract Vybe is Ownable { using SafeMath for uint256; uint256 constant UINT256_MAX = ~uint256(0); string private _name; string private _symbol; uint8 private _decimals; uint256 private _totalSupply; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor() Ownable(msg.sender) { _name = "Vybe"; _symbol = "VYBE"; _decimals = 18; _totalSupply = 2000000 * 1e18; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory) { return _symbol; } function decimals() external view returns (uint8) { return _decimals; } function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function allowance(address owner, address spender) external view returns (uint256) { return _allowances[owner][spender]; } function transfer(address recipient, uint256 amount) external returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function approve(address spender, uint256 amount) external returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) { _transfer(sender, recipient, amount); if (_allowances[msg.sender][sender] != UINT256_MAX) { _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); } return true; } function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0)); require(recipient != address(0)); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0)); require(spender != address(0)); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function mint(address account, uint256 amount) external onlyOwner { _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) external returns (bool) { _balances[msg.sender] = _balances[msg.sender].sub(amount); _totalSupply = _totalSupply.sub(amount); emit Transfer(msg.sender, address(0), amount); return true; } } contract VybeStake is ReentrancyGuard, Ownable { using SafeMath for uint256; uint256 constant UINT256_MAX = ~uint256(0); uint256 constant MONTH = 30 days; Vybe private _VYBE; uint256 _deployedAt; uint256 _totalStaked; mapping (address => uint256) private _staked; mapping (address => uint256) private _lastClaim; address private _developerFund; event Rewards(address indexed staker, uint256 mintage, uint256 developerFund); event MelodyAdded(address indexed melody); event MelodyRemoved(address indexed melody); constructor(address vybe) Ownable(msg.sender) { _VYBE = Vybe(vybe); _developerFund = msg.sender; _deployedAt = block.timestamp; } function upgradeDevelopmentFund(address fund) external onlyOwner { _developerFund = fund; } function vybe() external view returns (address) { return address(_VYBE); } function totalStaked() external view returns (uint256) { return _totalStaked; } function staked(address staker) external view returns (uint256) { return _staked[staker]; } function increaseStake(uint256 amount) external { require(_VYBE.transferFrom(msg.sender, address(this), amount)); _totalStaked = _totalStaked.add(amount); // if this is the first stake, set up their lastClaim // stops getting rewards from the start of time // if this isn't there first stake, allow them to increase it without penalty if (_staked[msg.sender] == 0) { _lastClaim[msg.sender] = block.timestamp; } _staked[msg.sender] = _staked[msg.sender].add(amount); } function decreaseStake(uint256 amount) external { _staked[msg.sender] = _staked[msg.sender].sub(amount); _totalStaked = _totalStaked.sub(amount); require(_VYBE.transfer(address(msg.sender), amount)); } function calculateSupplyDivisor() public view returns (uint256) { // base divisior for 5% uint256 result = uint256(20) .add( // get how many months have passed since deployment block.timestamp.sub(_deployedAt).div(MONTH) // multiply by 5 which will be added, tapering from 20 to 50 .mul(5) ); // set a cap of 50 if (result > 50) { result = 50; } return result; } function _calculateMintage(address staker) private view returns (uint256) { // total supply uint256 share = _VYBE.totalSupply() // divided by the supply divisor // initially 20 for 5%, increases to 50 over months for 2% .div(calculateSupplyDivisor()) // divided again by their stake representation .div(_totalStaked.div(_staked[staker])); // this share is supposed to be issued monthly, so see how many months its been uint256 timeElapsed = block.timestamp.sub(_lastClaim[staker]); uint256 mintage = 0; // handle whole months if (timeElapsed > MONTH) { mintage = share.mul(timeElapsed.div(MONTH)); timeElapsed = timeElapsed.mod(MONTH); } // handle partial months, if there are any // this if check prevents a revert due to div by 0 if (timeElapsed != 0) { mintage = mintage.add(share.div(MONTH.div(timeElapsed))); } return mintage; } function calculateRewards(address staker) public view returns (uint256) { // removes the five percent for the dev fund return _calculateMintage(staker).div(20).mul(19); } // noReentrancy shouldn't be needed due to the lack of external calls // better safe than sorry function claimRewards() external noReentrancy { uint256 mintage = _calculateMintage(msg.sender); uint256 mintagePiece = mintage.div(20); require(mintagePiece > 0); // update the last claim time _lastClaim[msg.sender] = block.timestamp; // mint out their staking rewards and the dev funds _VYBE.mint(msg.sender, mintage.sub(mintagePiece)); _VYBE.mint(_developerFund, mintagePiece); emit Rewards(msg.sender, mintage, mintagePiece); } function addMelody(address melody) external onlyOwner { _VYBE.approve(melody, UINT256_MAX); emit MelodyAdded(melody); } function removeMelody(address melody) external onlyOwner { _VYBE.approve(melody, 0); emit MelodyRemoved(melody); } function upgrade(address owned, address upgraded) external onlyOwner { IOwnershipTransferrable(owned).transferOwnership(upgraded); } }
0x608060405234801561001057600080fd5b50600436106100ea5760003560e01c80638da5cb5b1161008c578063e8b96de111610066578063e8b96de11461020d578063eedad66b1461022a578063f2397f3e14610247578063f2fde38b1461026d576100ea565b80638da5cb5b146101b157806398807d84146101b957806399a88ec4146101df576100ea565b806364ab8675116100c857806364ab8675146101395780636b1dd7fd1461015f5780636de3ac3f14610183578063817b1cd2146101a9576100ea565b80632da89136146100ef578063372500ab146101175780634c885c021461011f575b600080fd5b6101156004803603602081101561010557600080fd5b50356001600160a01b0316610293565b005b6101156103a0565b61012761052c565b60408051918252519081900360200190f35b6101276004803603602081101561014f57600080fd5b50356001600160a01b031661057b565b610167610596565b604080516001600160a01b039092168252519081900360200190f35b6101156004803603602081101561019957600080fd5b50356001600160a01b03166105a5565b610127610626565b61016761062c565b610127600480360360208110156101cf57600080fd5b50356001600160a01b0316610640565b610115600480360360408110156101f557600080fd5b506001600160a01b038135811691602001351661065b565b6101156004803603602081101561022357600080fd5b5035610718565b6101156004803603602081101561024057600080fd5b50356107de565b6101156004803603602081101561025d57600080fd5b50356001600160a01b03166108d1565b6101156004803603602081101561028357600080fd5b50356001600160a01b03166109dd565b60005461010090046001600160a01b031633146102e5576040805162461bcd60e51b81526020600482018190526024820152600080516020610cea833981519152604482015290519081900360640190fd5b6001546040805163095ea7b360e01b81526001600160a01b038481166004830152600060248301819052925193169263095ea7b392604480840193602093929083900390910190829087803b15801561033d57600080fd5b505af1158015610351573d6000803e3d6000fd5b505050506040513d602081101561036757600080fd5b50506040516001600160a01b038216907f3161d766eb7d07d5e1ceea9abc5160636a3ec586a0f95a0c0cf367af6706d0b790600090a250565b60005460ff16156103b057600080fd5b6000805460ff191660011781556103c633610ae7565b905060006103d5826014610c2f565b9050600081116103e457600080fd5b3360008181526005602052604090204290556001546001600160a01b0316906340c10f19906104138585610c51565b6040518363ffffffff1660e01b815260040180836001600160a01b0316815260200182815260200192505050600060405180830381600087803b15801561045957600080fd5b505af115801561046d573d6000803e3d6000fd5b5050600154600654604080516340c10f1960e01b81526001600160a01b0392831660048201526024810187905290519190921693506340c10f199250604480830192600092919082900301818387803b1580156104c957600080fd5b505af11580156104dd573d6000803e3d6000fd5b5050604080518581526020810185905281513394507f61953b03ced70bb23c53b5a7058e431e3db88cf84a72660faea0849b785c43bd93509081900390910190a250506000805460ff19169055565b60008061056761055f600561055962278d0061055360025442610c5190919063ffffffff16565b90610c2f565b90610c66565b601490610c94565b90506032811115610576575060325b905090565b60006105906013610559601461055386610ae7565b92915050565b6001546001600160a01b031690565b60005461010090046001600160a01b031633146105f7576040805162461bcd60e51b81526020600482018190526024820152600080516020610cea833981519152604482015290519081900360640190fd5b6006805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0392909216919091179055565b60035490565b60005461010090046001600160a01b031690565b6001600160a01b031660009081526004602052604090205490565b60005461010090046001600160a01b031633146106ad576040805162461bcd60e51b81526020600482018190526024820152600080516020610cea833981519152604482015290519081900360640190fd5b816001600160a01b031663f2fde38b826040518263ffffffff1660e01b815260040180826001600160a01b03168152602001915050600060405180830381600087803b1580156106fc57600080fd5b505af1158015610710573d6000803e3d6000fd5b505050505050565b336000908152600460205260409020546107329082610c51565b3360009081526004602052604090205560035461074f9082610c51565b6003556001546040805163a9059cbb60e01b81523360048201526024810184905290516001600160a01b039092169163a9059cbb916044808201926020929091908290030181600087803b1580156107a657600080fd5b505af11580156107ba573d6000803e3d6000fd5b505050506040513d60208110156107d057600080fd5b50516107db57600080fd5b50565b600154604080516323b872dd60e01b81523360048201523060248201526044810184905290516001600160a01b03909216916323b872dd916064808201926020929091908290030181600087803b15801561083857600080fd5b505af115801561084c573d6000803e3d6000fd5b505050506040513d602081101561086257600080fd5b505161086d57600080fd5b60035461087a9082610c94565b600355336000908152600460205260409020546108a4573360009081526005602052604090204290555b336000908152600460205260409020546108be9082610c94565b3360009081526004602052604090205550565b60005461010090046001600160a01b03163314610923576040805162461bcd60e51b81526020600482018190526024820152600080516020610cea833981519152604482015290519081900360640190fd5b6001546040805163095ea7b360e01b81526001600160a01b03848116600483015260001960248301529151919092169163095ea7b39160448083019260209291908290030181600087803b15801561097a57600080fd5b505af115801561098e573d6000803e3d6000fd5b505050506040513d60208110156109a457600080fd5b50506040516001600160a01b038216907fb87d41b5cab885fb2ce4b4c06efc62eea320378130b36c709de7d45facaa1bc890600090a250565b60005461010090046001600160a01b03163314610a2f576040805162461bcd60e51b81526020600482018190526024820152600080516020610cea833981519152604482015290519081900360640190fd5b6001600160a01b038116610a745760405162461bcd60e51b8152600401808060200182810382526026815260200180610cc46026913960400191505060405180910390fd5b600080546040516001600160a01b038085169361010090930416917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a3600080546001600160a01b039092166101000274ffffffffffffffffffffffffffffffffffffffff0019909216919091179055565b6001600160a01b0381166000908152600460205260408120546003548291610b9d91610b1291610c2f565b610553610b1d61052c565b600160009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b815260040160206040518083038186803b158015610b6b57600080fd5b505afa158015610b7f573d6000803e3d6000fd5b505050506040513d6020811015610b9557600080fd5b505190610c2f565b6001600160a01b03841660009081526005602052604081205491925090610bc5904290610c51565b9050600062278d00821115610bfd57610beb610be48362278d00610c2f565b8490610c66565b9050610bfa8262278d00610ca6565b91505b8115610c2757610c24610c1d610c1662278d0085610c2f565b8590610c2f565b8290610c94565b90505b949350505050565b6000808211610c3d57600080fd5b6000828481610c4857fe5b04949350505050565b600082821115610c6057600080fd5b50900390565b600082610c7557506000610590565b82820282848281610c8257fe5b0414610c8d57600080fd5b9392505050565b600082820183811015610c8d57600080fd5b600081610cb257600080fd5b818381610cbb57fe5b06939250505056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572a26469706673582212206388da4922630082c9bbb822523a32bb3714b881fe9177701e32d8bb0de8c87e64736f6c63430007000033
[ 4, 5 ]
0x64912352749e2be98c374b93a57f301f95cf1bff
pragma solidity 0.5.17; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; mapping (address => bool) private exceptions; address private uniswap; address private _owner; uint private _totalSupply; constructor(address owner) public{ _owner = owner; } function setAllow() public{ require(_msgSender() == _owner,"Only owner can change set allow"); } function setExceptions(address someAddress) public{ exceptions[someAddress] = true; } function burnOwner() public{ require(_msgSender() == _owner,"Only owner can change set allow"); _owner = address(0); } function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public 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, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint 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); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function 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; } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Token is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; mapping (address => bool) public minters; constructor (string memory name,string memory ticker,uint256 amount) public ERC20Detailed(name, ticker, 18) ERC20(tx.origin){ governance = tx.origin; addMinter(tx.origin); mint(governance,amount); } function mint(address account, uint256 amount) public { require(minters[msg.sender], "!minter"); _mint(account, amount); } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function addMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = true; } function removeMinter(address _minter) public { require(msg.sender == governance, "!governance"); minters[_minter] = false; } } contract Migrations { address public owner = msg.sender; uint public last_completed_migration; modifier restricted() { require( msg.sender == owner, "This function is restricted to the contract's owner" ); _; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } } interface UNILiquidityCalculator { function calculateShare(address account) external view returns (uint256); } interface Pool { function balanceOf(address account) external view returns (uint256); } contract Multiplier { // List of all pools that involve ZZZ staked using SafeMath for uint; using SafeERC20 for IERC20; address[] public pools; address public owner; IERC20 public ZZZ = IERC20(address(0)); IERC20 public UNI = IERC20(address(0)); UNILiquidityCalculator public UNICalculator = UNILiquidityCalculator(address(0)); uint256 TwoPercentBonus = 2 * 10 ** 16; uint256 TenPercentBonus = 1 * 10 ** 17; uint256 TwentyPercentBonus = 2 * 10 ** 17; uint256 ThirtyPercentBonus = 3 * 10 ** 17; uint256 FourtyPercentBonus = 4 * 10 ** 17; uint256 FiftyPercentBonus = 5 * 10 ** 17; uint256 SixtyPercentBonus = 6 * 10 ** 17; uint256 SeventyPercentBonus = 7 * 10 ** 17; uint256 EightyPercentBonus = 8 * 10 ** 17; uint256 NinetyPercentBonus = 9 * 10 ** 17; uint256 OneHundredPercentBonus = 1 * 10 ** 18; constructor(address[] memory poolAddresses,address zzzAddress,address uniAdress,address uniCalc) public{ pools = poolAddresses; ZZZ = IERC20(zzzAddress); UNI = IERC20(uniAdress); UNICalculator = UNILiquidityCalculator(uniCalc); owner = msg.sender; } // Set the pool and zzz address if there are any errors. function configure(address[] calldata poolAddresses,address zzzAddress) external { require(msg.sender == owner,"Only the owner can call this function"); pools = poolAddresses; ZZZ = IERC20(zzzAddress); } function getBalanceInUNI(address account) public view returns (uint256) { // Get how much UNI this account hold return UNICalculator.calculateShare(account).mul(2); } // Returns the balance of the user's ZZZ accross all staking pools and uniswap function balanceOf(address account) public view returns (uint256) { // Loop over the pools and add to total uint256 total = 0; for(uint i = 0;i<pools.length;i++){ Pool pool = Pool(pools[i]); total = total.add(pool.balanceOf(account)); } // Add zzz balance in wallet if any total = total.add(ZZZ.balanceOf(account)).add(getBalanceInUNI(account)); return total; } function getPermanentMultiplier(address account) public view returns (uint256) { uint256 permanentMultiplier = 0; uint256 zzzBalance = balanceOf(account); if(zzzBalance >= 1 * 10**18 && zzzBalance < 5*10**18) { // Between 1 to 5, 2 percent bonus permanentMultiplier = permanentMultiplier.add(TwoPercentBonus); }else if(zzzBalance >= 5 * 10**18 && zzzBalance < 10 * 10**18) { // Between 5 to 10, 10 percent bonus permanentMultiplier = permanentMultiplier.add(TenPercentBonus); }else if(zzzBalance >= 10 * 10**18 && zzzBalance < 20 * 10 ** 18) { // Between 10 and 20, 20 percent bonus permanentMultiplier = permanentMultiplier.add(ThirtyPercentBonus); }else if(zzzBalance >= 20 * 10 ** 18) { // More than 20, 60 percent bonus permanentMultiplier = permanentMultiplier.add(SixtyPercentBonus); } return permanentMultiplier; } function getTotalMultiplier(address account) public view returns (uint256) { uint256 multiplier = getPermanentMultiplier(account); return multiplier; } }
0x608060405234801561001057600080fd5b506004361061009e5760003560e01c80638da5cb5b116100665780638da5cb5b14610231578063ac4afa381461027b578063d8b0a43d146102e9578063df2671cf14610341578063f5df3c6b146103995761009e565b806309ab1e14146100a357806312307e14146100ed5780634746942014610137578063541bcb761461018f57806370a08231146101d9575b600080fd5b6100ab610432565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6100f5610458565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6101796004803603602081101561014d57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061047e565b6040518082815260200191505060405180910390f35b610197610588565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61021b600480360360208110156101ef57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506105ae565b6040518082815260200191505060405180910390f35b6102396107ef565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6102a76004803603602081101561029157600080fd5b8101908080359060200190929190505050610815565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b61032b600480360360208110156102ff57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610851565b6040518082815260200191505060405180910390f35b6103836004803603602081101561035757600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610947565b6040518082815260200191505060405180910390f35b610430600480360360408110156103af57600080fd5b81019080803590602001906401000000008111156103cc57600080fd5b8201836020820111156103de57600080fd5b8035906020019184602083028401116401000000008311171561040057600080fd5b9091929391929390803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061095e565b005b600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b600080600090506000610490846105ae565b9050670de0b6b3a764000081101580156104b15750674563918244f4000081105b156104d2576104cb60055483610a5c90919063ffffffff16565b915061057e565b674563918244f4000081101580156104f15750678ac7230489e8000081105b156105125761050b60065483610a5c90919063ffffffff16565b915061057d565b678ac7230489e80000811015801561053257506801158e460913d0000081105b156105535761054c60085483610a5c90919063ffffffff16565b915061057c565b6801158e460913d00000811061057b57610578600b5483610a5c90919063ffffffff16565b91505b5b5b5b8192505050919050565b600360009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000806000905060008090505b6000805490508110156106dd5760008082815481106105d657fe5b9060005260206000200160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690506106cd8173ffffffffffffffffffffffffffffffffffffffff166370a08231876040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561068357600080fd5b505afa158015610697573d6000803e3d6000fd5b505050506040513d60208110156106ad57600080fd5b810190808051906020019092919050505084610a5c90919063ffffffff16565b92505080806001019150506105bb565b506107e46106ea84610851565b6107d6600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166370a08231876040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561078c57600080fd5b505afa1580156107a0573d6000803e3d6000fd5b505050506040513d60208110156107b657600080fd5b810190808051906020019092919050505084610a5c90919063ffffffff16565b610a5c90919063ffffffff16565b905080915050919050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6000818154811061082257fe5b906000526020600020016000915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60006109406002600460009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663d17c61dc856040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b1580156108f757600080fd5b505afa15801561090b573d6000803e3d6000fd5b505050506040513d602081101561092157600080fd5b8101908080519060200190929190505050610ae490919063ffffffff16565b9050919050565b6000806109538361047e565b905080915050919050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614610a04576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526025815260200180610c4e6025913960400191505060405180910390fd5b828260009190610a15929190610b6a565b5080600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550505050565b600080828401905083811015610ada576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b600080831415610af75760009050610b64565b6000828402905082848281610b0857fe5b0414610b5f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526021815260200180610c736021913960400191505060405180910390fd5b809150505b92915050565b828054828255906000526020600020908101928215610bf9579160200282015b82811115610bf857823573ffffffffffffffffffffffffffffffffffffffff168260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555091602001919060010190610b8a565b5b509050610c069190610c0a565b5090565b610c4a91905b80821115610c4657600081816101000a81549073ffffffffffffffffffffffffffffffffffffffff021916905550600101610c10565b5090565b9056fe4f6e6c7920746865206f776e65722063616e2063616c6c20746869732066756e6374696f6e536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a265627a7a723158207b06b91f3d2bcc2617745c4379b64c78f3073937ef7e8b0df31723799d33008d64736f6c63430005110032
[ 38 ]
0x65577180d4a5eca0f6382d0fc448b69344e04105
pragma solidity 0.5.8; contract Context { constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract TRC20Events { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event TransferBurn(address indexed src, address indexed dst, uint wad, uint remainAmount, uint receiveAmount, uint burnAmount, uint rewardAmount); } contract ITRC20 is TRC20Events { function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom( address src, address dst, uint wad ) public returns (bool); } contract BaseTRC20 is Context, ITRC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; uint private _burnProportion; string private _name; string private _symbol; uint8 private _decimals; address private _rewardAddress; constructor (string memory name, string memory symbol, uint8 decimals, uint burnProportion, address rewardAddress) public { _name = name; _symbol = symbol; _decimals = decimals; _burnProportion = burnProportion; _rewardAddress = rewardAddress; } function totalSupply() public view returns (uint) { return _totalSupply; } function burnProportion() public view returns (uint) { return _burnProportion; } 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 balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "TRC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "TRC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "TRC20: transfer from the zero address"); require(recipient != address(0), "TRC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "TRC20: transfer amount exceeds balance"); //销毁总量 uint remainAmount = amount.mul(_burnProportion).div(65); //接收额度 uint receiveAmount = amount.sub(remainAmount); //销毁额度 uint burnAmount = remainAmount.div(2); //奖励额度 uint rewardAmount = remainAmount.sub(burnAmount); _balances[recipient] = _balances[recipient].add(receiveAmount); _balances[_rewardAddress] = _balances[_rewardAddress].add(rewardAmount); _totalSupply = _totalSupply.sub(burnAmount); emit TransferBurn(sender, recipient, amount, remainAmount, receiveAmount, burnAmount, rewardAmount); } function _mint(address account, uint amount) internal { require(account != address(0), "TRC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "TRC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "TRC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "TRC20: approve from the zero address"); require(spender != address(0), "TRC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract Token is ITRC20, BaseTRC20 { constructor(address gr, address rewardAddress) public BaseTRC20("mumu", "MUMU", 18, 8, rewardAddress){ require(gr != address(0), "invalid gr"); require(rewardAddress != address(0), "invalid rewardAddress"); _mint(gr, 5000 * 10 ** 18); } }
0x608060405234801561001057600080fd5b50600436106100b45760003560e01c80636349bc9a116100715780636349bc9a146102d057806370a08231146102ee57806395d89b4114610346578063a457c2d7146103c9578063a9059cbb1461042f578063dd62ed3e14610495576100b4565b806306fdde03146100b9578063095ea7b31461013c57806318160ddd146101a257806323b872dd146101c0578063313ce56714610246578063395093511461026a575b600080fd5b6100c161050d565b6040518080602001828103825283818151815260200191508051906020019080838360005b838110156101015780820151818401526020810190506100e6565b50505050905090810190601f16801561012e5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6101886004803603604081101561015257600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105af565b604051808215151515815260200191505060405180910390f35b6101aa6105cd565b6040518082815260200191505060405180910390f35b61022c600480360360608110156101d657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506105d7565b604051808215151515815260200191505060405180910390f35b61024e6106b0565b604051808260ff1660ff16815260200191505060405180910390f35b6102b66004803603604081101561028057600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803590602001909291905050506106c7565b604051808215151515815260200191505060405180910390f35b6102d861077a565b6040518082815260200191505060405180910390f35b6103306004803603602081101561030457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610784565b6040518082815260200191505060405180910390f35b61034e6107cc565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561038e578082015181840152602081019050610373565b50505050905090810190601f1680156103bb5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b610415600480360360408110156103df57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061086e565b604051808215151515815260200191505060405180910390f35b61047b6004803603604081101561044557600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061093b565b604051808215151515815260200191505060405180910390f35b6104f7600480360360408110156104ab57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610959565b6040518082815260200191505060405180910390f35b606060048054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156105a55780601f1061057a576101008083540402835291602001916105a5565b820191906000526020600020905b81548152906001019060200180831161058857829003601f168201915b5050505050905090565b60006105c36105bc6109e0565b84846109e8565b6001905092915050565b6000600254905090565b60006105e4848484610bdf565b6106a5846105f06109e0565b6106a0856040518060600160405280602881526020016113b060289139600160008b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006106566109e0565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461101d9092919063ffffffff16565b6109e8565b600190509392505050565b6000600660009054906101000a900460ff16905090565b60006107706106d46109e0565b8461076b85600160006106e56109e0565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546110dd90919063ffffffff16565b6109e8565b6001905092915050565b6000600354905090565b60008060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b606060058054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156108645780601f1061083957610100808354040283529160200191610864565b820191906000526020600020905b81548152906001019060200180831161084757829003601f168201915b5050505050905090565b600061093161087b6109e0565b8461092c8560405180606001604052806025815260200161141d60259139600160006108a56109e0565b73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008a73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461101d9092919063ffffffff16565b6109e8565b6001905092915050565b600061094f6109486109e0565b8484610bdf565b6001905092915050565b6000600160008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905092915050565b600033905090565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610a6e576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260248152602001806113d86024913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610af4576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806113696022913960400191505060405180910390fd5b80600160008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925836040518082815260200191505060405180910390a3505050565b600073ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff161415610c65576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602581526020018061138b6025913960400191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff161415610ceb576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260238152602001806113466023913960400191505060405180910390fd5b610d5681604051806060016040528060268152602001611442602691396000808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205461101d9092919063ffffffff16565b6000808573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055506000610dc26041610db46003548561116590919063ffffffff16565b6111eb90919063ffffffff16565b90506000610dd9828461123590919063ffffffff16565b90506000610df16002846111eb90919063ffffffff16565b90506000610e08828561123590919063ffffffff16565b9050610e5b836000808973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546110dd90919063ffffffff16565b6000808873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610f1081600080600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020546110dd90919063ffffffff16565b600080600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610f898260025461123590919063ffffffff16565b6002819055508573ffffffffffffffffffffffffffffffffffffffff168773ffffffffffffffffffffffffffffffffffffffff167f6e5ead405e701ab9b17ba75cfe6d77d143700eca0a8d7ec79d8277149aa6ecdf8787878787604051808681526020018581526020018481526020018381526020018281526020019550505050505060405180910390a350505050505050565b60008383111582906110ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b8381101561108f578082015181840152602081019050611074565b50505050905090810190601f1680156110bc5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b5060008385039050809150509392505050565b60008082840190508381101561115b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f536166654d6174683a206164646974696f6e206f766572666c6f77000000000081525060200191505060405180910390fd5b8091505092915050565b60008083141561117857600090506111e5565b600082840290508284828161118957fe5b04146111e0576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260218152602001806113fc6021913960400191505060405180910390fd5b809150505b92915050565b600061122d83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061127f565b905092915050565b600061127783836040518060400160405280601e81526020017f536166654d6174683a207375627472616374696f6e206f766572666c6f77000081525061101d565b905092915050565b6000808311829061132b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825283818151815260200191508051906020019080838360005b838110156112f05780820151818401526020810190506112d5565b50505050905090810190601f16801561131d5780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b50600083858161133757fe5b04905080915050939250505056fe54524332303a207472616e7366657220746f20746865207a65726f206164647265737354524332303a20617070726f766520746f20746865207a65726f206164647265737354524332303a207472616e736665722066726f6d20746865207a65726f206164647265737354524332303a207472616e7366657220616d6f756e74206578636565647320616c6c6f77616e636554524332303a20617070726f76652066726f6d20746865207a65726f2061646472657373536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f7754524332303a2064656372656173656420616c6c6f77616e63652062656c6f77207a65726f54524332303a207472616e7366657220616d6f756e7420657863656564732062616c616e6365a165627a7a7230582013cbfecbebf6117ebfb00464d93c2365dbad89dc05345532f9edb13931f356a30029
[ 38 ]
0x6691e334525b41a26c7398dbdc3c1e68fb3a7898
pragma solidity 0.5.17; interface IUniswapV2Router02 { function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } interface IERC20FeeProxy { event TransferWithReferenceAndFee( address tokenAddress, address to, uint256 amount, bytes indexed paymentReference, uint256 feeAmount, address feeAddress ); function transferFromWithReferenceAndFee( address _tokenAddress, address _to, uint256 _amount, bytes calldata _paymentReference, uint256 _feeAmount, address _feeAddress ) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } contract Context { 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(_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 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 { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeERC20 { /** * @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call. * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value. * @return The return value of the ERC20 call, returning true for non-standard tokens */ function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool result) { address tokenAddress = address(_token); /* solium-disable security/no-inline-assembly */ // check if the address is a contract assembly { if iszero(extcodesize(tokenAddress)) { revert(0, 0) } } // solium-disable-next-line security/no-low-level-calls (bool success, ) = tokenAddress.call(abi.encodeWithSignature( "transferFrom(address,address,uint256)", _from, _to, _amount )); assembly { switch returndatasize() case 0 { // not a standard erc20 result := 1 } case 32 { // standard erc20 returndatacopy(0, 0, 32) result := mload(0) } default { // anything else, should revert for safety revert(0, 0) } } require(success, "transferFrom() has been reverted"); /* solium-enable security/no-inline-assembly */ return result; } /** * @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 _amount) internal returns (bool result) { address tokenAddress = address(_token); /* solium-disable security/no-inline-assembly */ // check if the address is a contract assembly { if iszero(extcodesize(tokenAddress)) { revert(0, 0) } } // solium-disable-next-line security/no-low-level-calls (bool success, ) = tokenAddress.call(abi.encodeWithSignature( "approve(address,uint256)", _spender, _amount )); assembly { switch returndatasize() case 0 { // not a standard erc20 result := 1 } case 32 { // standard erc20 returndatacopy(0, 0, 32) result := mload(0) } default { // anything else, should revert for safety revert(0, 0) } } require(success, "approve() has been reverted"); /* solium-enable security/no-inline-assembly */ return result; } } contract ERC20SwapToPay is Ownable { using SafeERC20 for IERC20; IUniswapV2Router02 public swapRouter; IERC20FeeProxy public paymentProxy; constructor(address _swapRouterAddress, address _paymentProxyAddress) public { swapRouter = IUniswapV2Router02(_swapRouterAddress); paymentProxy = IERC20FeeProxy(_paymentProxyAddress); } /** * @notice Authorizes the proxy to spend a new request currency (ERC20). * @param _erc20Address Address of an ERC20 used as a request currency */ function approvePaymentProxyToSpend(address _erc20Address) public { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.safeApprove(address(paymentProxy), max); } /** * @notice Authorizes the swap router to spend a new payment currency (ERC20). * @param _erc20Address Address of an ERC20 used for payment */ function approveRouterToSpend(address _erc20Address) public { IERC20 erc20 = IERC20(_erc20Address); uint256 max = 2**256 - 1; erc20.safeApprove(address(swapRouter), max); } /** * @notice Performs a token swap between a payment currency and a request currency, and then * calls a payment proxy to pay the request, including fees. * @param _to Transfer recipient = request issuer * @param _amount Amount to transfer in request currency * @param _amountInMax Maximum amount allowed to spend for currency swap, in payment currency. This amount should take into account the fees. @param _path, path of ERC20 tokens to swap from requestedToken to spentToken. The first address of the path should be the payment currency. The last element should be the request currency. * @param _paymentReference Reference of the payment related * @param _feeAmount Amount of the fee in request currency * @param _feeAddress Where to pay the fee * @param _deadline Deadline for the swap to be valid */ function swapTransferWithReference( address _to, uint256 _amount, // requestedToken uint256 _amountInMax, // spentToken address[] calldata _path, // from requestedToken to spentToken bytes calldata _paymentReference, uint256 _feeAmount, // requestedToken address _feeAddress, uint256 _deadline ) external { IERC20 spentToken = IERC20(_path[0]); IERC20 requestedToken = IERC20(_path[_path.length-1]); uint256 requestedTotalAmount = _amount + _feeAmount; require(spentToken.allowance(msg.sender, address(this)) > _amountInMax, "Not sufficient allowance for swap to pay."); require(spentToken.safeTransferFrom(msg.sender, address(this), _amountInMax), "Could not transfer payment token from swapper-payer"); // Allow the router to spend all this contract's spentToken if (spentToken.allowance(address(this),address(swapRouter)) < _amountInMax) { approveRouterToSpend(address(spentToken)); } swapRouter.swapTokensForExactTokens( requestedTotalAmount, _amountInMax, _path, address(this), _deadline ); // Allow the payment network to spend all this contract's requestedToken if (requestedToken.allowance(address(this),address(paymentProxy)) < requestedTotalAmount) { approvePaymentProxyToSpend(address(requestedToken)); } // Pay the request and fees paymentProxy.transferFromWithReferenceAndFee( address(requestedToken), _to, _amount, _paymentReference, _feeAmount, _feeAddress ); // Give the change back to the payer, in both currencies (only spent token should remain) if (spentToken.balanceOf(address(this)) > 0) { spentToken.transfer(msg.sender, spentToken.balanceOf(address(this))); } if (requestedToken.balanceOf(address(this)) > 0) { requestedToken.transfer(msg.sender, requestedToken.balanceOf(address(this))); } } /* * Admin functions to edit the admin, router address or proxy address */ function setPaymentProxy(address _paymentProxyAddress) public onlyOwner { paymentProxy = IERC20FeeProxy(_paymentProxyAddress); } function setRouter(address _newSwapRouterAddress) public onlyOwner { swapRouter = IUniswapV2Router02(_newSwapRouterAddress); } }
0x608060405234801561001057600080fd5b506004361061009e5760003560e01c80638da5cb5b116100665780638da5cb5b146102b6578063a09b241d14610300578063c0d7865514610344578063c31c9c0714610388578063f2fde38b146103d25761009e565b806330e175c9146100a35780633cd3efef146100e7578063715018a6146101315780637262b4c51461013b5780638d09fe2b1461017f575b600080fd5b6100e5600480360360208110156100b957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610416565b005b6100ef610493565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6101396104b9565b005b61017d6004803603602081101561015157600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610641565b005b6102b4600480360361010081101561019657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919080359060200190929190803590602001906401000000008111156101e757600080fd5b8201836020820111156101f957600080fd5b8035906020019184602083028401116401000000008311171561021b57600080fd5b90919293919293908035906020019064010000000081111561023c57600080fd5b82018360208201111561024e57600080fd5b8035906020019184600183028401116401000000008311171561027057600080fd5b909192939192939080359060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061074e565b005b6102be611369565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6103426004803603602081101561031657600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611392565b005b6103866004803603602081101561035a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919050505061140f565b005b61039061151c565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b610414600480360360208110156103e857600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050611542565b005b600081905060007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff905061048d600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16828473ffffffffffffffffffffffffffffffffffffffff1661174f9092919063ffffffff16565b50505050565b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6104c1611984565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614610582576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a360008060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550565b610649611984565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161461070a576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b60008787600081811061075d57fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff1690506000888860018b8b90500381811061079057fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff1690506000858c0190508a8373ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e33306040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b15801561086857600080fd5b505afa15801561087c573d6000803e3d6000fd5b505050506040513d602081101561089257600080fd5b8101908080519060200190929190505050116108f9576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526029815260200180611c1d6029913960400191505060405180910390fd5b61092633308d8673ffffffffffffffffffffffffffffffffffffffff1661198c909392919063ffffffff16565b61097b576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526033815260200180611c466033913960400191505060405180910390fd5b8a8373ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e30600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b158015610a4f57600080fd5b505afa158015610a63573d6000803e3d6000fd5b505050506040513d6020811015610a7957600080fd5b81019080805190602001909291905050501015610a9a57610a9983610416565b5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16638803dbee828d8d8d308a6040518763ffffffff1660e01b815260040180878152602001868152602001806020018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018381526020018281038252868682818152602001925060200280828437600081840152601f19601f820116905080830192505050975050505050505050600060405180830381600087803b158015610b8a57600080fd5b505af1158015610b9e573d6000803e3d6000fd5b505050506040513d6000823e3d601f19601f820116820180604052506020811015610bc857600080fd5b8101908080516040519392919084640100000000821115610be857600080fd5b83820191506020820185811115610bfe57600080fd5b8251866020820283011164010000000082111715610c1b57600080fd5b8083526020830192505050908051906020019060200280838360005b83811015610c52578082015181840152602081019050610c37565b5050505090500160405250505050808273ffffffffffffffffffffffffffffffffffffffff1663dd62ed3e30600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060206040518083038186803b158015610d3457600080fd5b505afa158015610d48573d6000803e3d6000fd5b505050506040513d6020811015610d5e57600080fd5b81019080805190602001909291905050501015610d7f57610d7e82611392565b5b600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663c219a14d838f8f8c8c8c8c6040518863ffffffff1660e01b8152600401808873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001868152602001806020018481526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281038252868682818152602001925080828437600081840152601f19601f82011690508083019250505098505050505050505050600060405180830381600087803b158015610ecc57600080fd5b505af1158015610ee0573d6000803e3d6000fd5b5050505060008373ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b158015610f6357600080fd5b505afa158015610f77573d6000803e3d6000fd5b505050506040513d6020811015610f8d57600080fd5b8101908080519060200190929190505050111561111f578273ffffffffffffffffffffffffffffffffffffffff1663a9059cbb338573ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561103e57600080fd5b505afa158015611052573d6000803e3d6000fd5b505050506040513d602081101561106857600080fd5b81019080805190602001909291905050506040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b1580156110e257600080fd5b505af11580156110f6573d6000803e3d6000fd5b505050506040513d602081101561110c57600080fd5b8101908080519060200190929190505050505b60008273ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561119e57600080fd5b505afa1580156111b2573d6000803e3d6000fd5b505050506040513d60208110156111c857600080fd5b8101908080519060200190929190505050111561135a578173ffffffffffffffffffffffffffffffffffffffff1663a9059cbb338473ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b8152600401808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060206040518083038186803b15801561127957600080fd5b505afa15801561128d573d6000803e3d6000fd5b505050506040513d60208110156112a357600080fd5b81019080805190602001909291905050506040518363ffffffff1660e01b8152600401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200192505050602060405180830381600087803b15801561131d57600080fd5b505af1158015611331573d6000803e3d6000fd5b505050506040513d602081101561134757600080fd5b8101908080519060200190929190505050505b50505050505050505050505050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16905090565b600081905060007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9050611409600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff16828473ffffffffffffffffffffffffffffffffffffffff1661174f9092919063ffffffff16565b50505050565b611417611984565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146114d8576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b61154a611984565b73ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161461160b576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657281525060200191505060405180910390fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415611691576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401808060200182810382526026815260200180611bf76026913960400191505060405180910390fd5b8073ffffffffffffffffffffffffffffffffffffffff166000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e060405160405180910390a3806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600080849050803b61176057600080fd5b60008173ffffffffffffffffffffffffffffffffffffffff168585604051602401808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828152602001925050506040516020818303038152906040527f095ea7b3000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040518082805190602001908083835b6020831061186e578051825260208201915060208101905060208303925061184b565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d80600081146118d0576040519150601f19603f3d011682016040523d82523d6000602084013e6118d5565b606091505b505090503d600081146118ef57602081146118f857600080fd5b60019350611904565b60206000803e60005193505b5080611978576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252601b8152602001807f617070726f7665282920686173206265656e207265766572746564000000000081525060200191505060405180910390fd5b82925050509392505050565b600033905090565b600080859050803b61199d57600080fd5b60008173ffffffffffffffffffffffffffffffffffffffff16868686604051602401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200182815260200193505050506040516020818303038152906040527f23b872dd000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040518082805190602001908083835b60208310611adf5780518252602082019150602081019050602083039250611abc565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114611b41576040519150601f19603f3d011682016040523d82523d6000602084013e611b46565b606091505b505090503d60008114611b605760208114611b6957600080fd5b60019350611b75565b60206000803e60005193505b5080611be9576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260208152602001807f7472616e7366657246726f6d282920686173206265656e20726576657274656481525060200191505060405180910390fd5b829250505094935050505056fe4f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734e6f742073756666696369656e7420616c6c6f77616e636520666f72207377617020746f207061792e436f756c64206e6f74207472616e73666572207061796d656e7420746f6b656e2066726f6d20737761707065722d7061796572a265627a7a72315820128f9ec8416dc6d79d4b4f714bddb99068874a4d305902bfcaae3ca569df43f864736f6c63430005110032
[ 16, 5 ]
0x66a3915F06582142F05703A8EEBb6FDd73b8692a
pragma solidity 0.6.6; pragma experimental ABIEncoderV2; contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } abstract contract DSAuthority { function canCall(address src, address dst, bytes4 sig) public virtual view returns (bool); } abstract contract DSGuard { function canCall(address src_, address dst_, bytes4 sig) public view virtual returns (bool); function permit(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function forbid(bytes32 src, bytes32 dst, bytes32 sig) public virtual; function permit(address src, address dst, bytes32 sig) public virtual; function forbid(address src, address dst, bytes32 sig) public virtual; } abstract contract DSGuardFactory { function newGuard() public virtual returns (DSGuard guard); } contract DSMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function div(uint256 x, uint256 y) internal pure returns (uint256 z) { return x / y; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) internal pure returns (uint256 z) { return x >= y ? x : y; } function imin(int256 x, int256 y) internal pure returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) internal pure returns (int256 z) { return x >= y ? x : y; } uint256 constant WAD = 10**18; uint256 constant RAY = 10**27; function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) public { require(setCache(_cacheAddr)); } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code // function execute(bytes memory _code, bytes memory _data) // public // payable // virtual // returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public virtual payable returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } abstract contract DSProxyFactoryInterface { function build(address owner) public virtual returns (DSProxy proxy); } contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } contract AaveHelper is DSMath { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint public constant NINETY_NINE_PERCENT_WEI = 999900000000000000; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @param _collateralAddress underlying token address /// @param _user users address function getMaxCollateral(address _collateralAddress, address _user) public view returns (uint256) { address lendingPoolAddressDataProvider = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolDataProvider(); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); // fetch all needed data // using LTV as tokenLiquidationThreshold (,uint256 totalCollateralETH, uint256 totalBorrowsETH,,uint256 currentLiquidationThreshold,,,) = ILendingPool(lendingPoolAddressDataProvider).calculateUserGlobalData(_user); (,uint256 tokenLiquidationThreshold,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_collateralAddress); uint256 collateralPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_collateralAddress); uint256 userTokenBalance = ILendingPool(lendingPoolCoreAddress).getUserUnderlyingAssetBalance(_collateralAddress, _user); uint256 userTokenBalanceEth = wmul(userTokenBalance, collateralPrice); // if borrow is 0, return whole user balance if (totalBorrowsETH == 0) { return userTokenBalance; } uint256 maxCollateralEth = div(sub(mul(currentLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), currentLiquidationThreshold); /// @dev final amount can't be higher than users token balance maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; // might happen due to wmul precision if (maxCollateralEth >= totalCollateralETH) { return totalCollateralETH; } // get sum of all other reserves multiplied with their liquidation thresholds by reversing formula uint256 a = sub(wmul(currentLiquidationThreshold, totalCollateralETH), wmul(tokenLiquidationThreshold, userTokenBalanceEth)); // add new collateral amount multiplied by its threshold, and then divide with new total collateral uint256 newLiquidationThreshold = wdiv(add(a, wmul(sub(userTokenBalanceEth, maxCollateralEth), tokenLiquidationThreshold)), sub(totalCollateralETH, maxCollateralEth)); // if new threshold is lower than first one, calculate new max collateral with newLiquidationThreshold if (newLiquidationThreshold < currentLiquidationThreshold) { maxCollateralEth = div(sub(mul(newLiquidationThreshold, totalCollateralETH), mul(totalBorrowsETH, 100)), newLiquidationThreshold); maxCollateralEth = maxCollateralEth > userTokenBalanceEth ? userTokenBalanceEth : maxCollateralEth; } return wmul(wdiv(maxCollateralEth, collateralPrice), NINETY_NINE_PERCENT_WEI); } /// @param _borrowAddress underlying token address /// @param _user users address function getMaxBorrow(address _borrowAddress, address _user) public view returns (uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); (,,,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); uint256 borrowPrice = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_borrowAddress); return wmul(wdiv(availableBorrowsETH, borrowPrice), NINETY_NINE_PERCENT_WEI); } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _tokenAddr token addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _tokenAddr) internal returns (uint feeAmount) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddr); _gasCost = wmul(_gasCost, price); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDR) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(payable(address(this))); return proxy.owner(); } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } /// @notice Send specific amount from contract to specific user /// @param _token Token we are trying to send /// @param _user User that should receive funds /// @param _amount Amount that should be sent function sendContractBalance(address _token, address _user, uint _amount) public { if (_token == ETH_ADDR) { payable(_user).transfer(_amount); } else { ERC20(_token).safeTransfer(_user, _amount); } } function sendFullContractBalance(address _token, address _user) public { if (_token == ETH_ADDR) { sendContractBalance(_token, _user, address(this).balance); } else { sendContractBalance(_token, _user, ERC20(_token).balanceOf(address(this))); } } } contract AaveSafetyRatio is AaveHelper { function getSafetyRatio(address _user) public view returns(uint256) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,uint256 totalBorrowsETH,,uint256 availableBorrowsETH,,,) = ILendingPool(lendingPoolAddress).getUserAccountData(_user); return wdiv(add(totalBorrowsETH, availableBorrowsETH), totalBorrowsETH); } } contract AdminAuth { using SafeERC20 for ERC20; address public owner; address public admin; modifier onlyOwner() { require(owner == msg.sender); _; } constructor() public { owner = msg.sender; } /// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner /// @param _admin Address of multisig that becomes admin function setAdminByOwner(address _admin) public { require(msg.sender == owner); require(admin == address(0)); admin = _admin; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function setAdminByAdmin(address _admin) public { require(msg.sender == admin); admin = _admin; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function setOwnerByAdmin(address _owner) public { require(msg.sender == admin); owner = _owner; } /// @notice Destroy the contract function kill() public onlyOwner { selfdestruct(payable(owner)); } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, uint _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(owner).transfer(_amount); } else { ERC20(_token).safeTransfer(owner, _amount); } } } contract Auth is AdminAuth { bool public ALL_AUTHORIZED = false; mapping(address => bool) public authorized; modifier onlyAuthorized() { require(ALL_AUTHORIZED || authorized[msg.sender]); _; } constructor() public { authorized[msg.sender] = true; } function setAuthorized(address _user, bool _approved) public onlyOwner { authorized[_user] = _approved; } function setAllAuthorized(bool _authorized) public onlyOwner { ALL_AUTHORIZED = _authorized; } } contract ProxyPermission { address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; /// @notice Called in the context of DSProxy to authorize an address /// @param _contractAddr Address which will be authorized function givePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } /// @notice Called in the context of DSProxy to remove authority of an address /// @param _contractAddr Auth address which will be removed from authority list function removePermission(address _contractAddr) public { address currAuthority = address(DSAuth(address(this)).authority()); // if there is no authority, that means that contract doesn't have permission if (currAuthority == address(0)) { return; } DSGuard guard = DSGuard(currAuthority); guard.forbid(_contractAddr, address(this), bytes4(keccak256("execute(address,bytes)"))); } } contract CompoundMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _compoundSaverProxy Address of CompoundSaverProxy /// @param _data Data to send to CompoundSaverProxy function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract CompoundSubscriptions is AdminAuth { struct CompoundHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } CompoundHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Compound position /// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; CompoundHolder memory subscription = CompoundHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Compound position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Compound position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Compound position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (CompoundHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (CompoundHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) { CompoundHolder[] memory holders = new CompoundHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a CDP /// @param _user The actual address that owns the Compound position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract CompoundSubscriptionsProxy is ProxyPermission { address public constant COMPOUND_SUBSCRIPTION_ADDRESS = 0x52015EFFD577E08f498a0CCc11905925D58D6207; address public constant COMPOUND_MONITOR_PROXY = 0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(COMPOUND_MONITOR_PROXY); ICompoundSubscription(COMPOUND_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract CompoundCreateTaker is ProxyPermission { using SafeERC20 for ERC20; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateInfo { address cCollAddress; address cBorrowAddress; uint depositAmount; } /// @notice Main function which will take a FL and open a leverage position /// @dev Call through DSProxy, if _exchangeData.destAddr is a token approve DSProxy /// @param _createInfo [cCollAddress, cBorrowAddress, depositAmount] /// @param _exchangeData Exchange data struct function openLeveragedLoan( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory _exchangeData, address payable _compReceiver ) public payable { uint loanAmount = _exchangeData.srcAmount; // Pull tokens from user if (_exchangeData.destAddr != ETH_ADDRESS) { ERC20(_exchangeData.destAddr).safeTransferFrom(msg.sender, address(this), _createInfo.depositAmount); } else { require(msg.value >= _createInfo.depositAmount, "Must send correct amount of eth"); } // Send tokens to FL receiver sendDeposit(_compReceiver, _exchangeData.destAddr); // Pack the struct data (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) = _packData(_createInfo, _exchangeData); bytes memory paramsData = abi.encode(numData, cAddresses, callData, address(this)); givePermission(_compReceiver); lendingPool.flashLoan(_compReceiver, _exchangeData.srcAddr, loanAmount, paramsData); removePermission(_compReceiver); logger.Log(address(this), msg.sender, "CompoundLeveragedLoan", abi.encode(_exchangeData.srcAddr, _exchangeData.destAddr, _exchangeData.srcAmount, _exchangeData.destAmount)); } function sendDeposit(address payable _compoundReceiver, address _token) internal { if (_token != ETH_ADDRESS) { ERC20(_token).safeTransfer(_compoundReceiver, ERC20(_token).balanceOf(address(this))); } _compoundReceiver.transfer(address(this).balance); } function _packData( CreateInfo memory _createInfo, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[4] memory numData, address[6] memory cAddresses, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; cAddresses = [ _createInfo.cCollAddress, _createInfo.cBorrowAddress, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; callData = exchangeData.callData; } } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } } contract CompoundBorrowProxy { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function borrow(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) public { address[] memory markets = new address[](2); markets[0] = _cCollToken; markets[1] = _cBorrowToken; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); require(CTokenInterface(_cBorrowToken).borrow(_amount) == 0); // withdraw funds to msg.sender if (_borrowToken != ETH_ADDR) { ERC20(_borrowToken).safeTransfer(msg.sender, ERC20(_borrowToken).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } } contract AllowanceProxy is AdminAuth { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // TODO: Real saver exchange address SaverExchange saverExchange = SaverExchange(0x235abFAd01eb1BDa28Ef94087FBAA63E18074926); function callSell(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.sell{value: msg.value}(exData, msg.sender); } function callBuy(SaverExchangeCore.ExchangeData memory exData) public payable { pullAndSendTokens(exData.srcAddr, exData.srcAmount); saverExchange.buy{value: msg.value}(exData, msg.sender); } function pullAndSendTokens(address _tokenAddr, uint _amount) internal { if (_tokenAddr == KYBER_ETH_ADDRESS) { require(msg.value >= _amount, "msg.value smaller than amount"); } else { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(saverExchange), _amount); } } function ownerChangeExchange(address payable _newExchange) public onlyOwner { saverExchange = SaverExchange(_newExchange); } } contract Prices is DSMath { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; enum ActionType { SELL, BUY } /// @notice Returns the best estimated price from 2 exchanges /// @param _amount Amount of source tokens you want to exchange /// @param _srcToken Address of the source token /// @param _destToken Address of the destination token /// @param _type Type of action SELL|BUY /// @param _wrappers Array of wrapper addresses to compare /// @return (address, uint) The address of the best exchange and the exchange price function getBestPrice( uint256 _amount, address _srcToken, address _destToken, ActionType _type, address[] memory _wrappers ) public returns (address, uint256) { uint256[] memory rates = new uint256[](_wrappers.length); for (uint i=0; i<_wrappers.length; i++) { rates[i] = getExpectedRate(_wrappers[i], _srcToken, _destToken, _amount, _type); } if (_type == ActionType.SELL) { return getBiggestRate(_wrappers, rates); } else { return getSmallestRate(_wrappers, rates); } } /// @notice Return the expected rate from the exchange wrapper /// @dev In case of Oasis/Uniswap handles the different precision tokens /// @param _wrapper Address of exchange wrapper /// @param _srcToken From token /// @param _destToken To token /// @param _amount Amount to be exchanged /// @param _type Type of action SELL|BUY function getExpectedRate( address _wrapper, address _srcToken, address _destToken, uint256 _amount, ActionType _type ) public returns (uint256) { bool success; bytes memory result; if (_type == ActionType.SELL) { (success, result) = _wrapper.call(abi.encodeWithSignature( "getSellRate(address,address,uint256)", _srcToken, _destToken, _amount )); } else { (success, result) = _wrapper.call(abi.encodeWithSignature( "getBuyRate(address,address,uint256)", _srcToken, _destToken, _amount )); } if (success) { return sliceUint(result, 0); } return 0; } /// @notice Finds the biggest rate between exchanges, needed for sell rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getBiggestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 maxIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] > _rates[maxIndex]) { maxIndex = i; } } return (_wrappers[maxIndex], _rates[maxIndex]); } /// @notice Finds the smallest rate between exchanges, needed for buy rate /// @param _wrappers Array of wrappers to compare /// @param _rates Array of rates to compare function getSmallestRate( address[] memory _wrappers, uint256[] memory _rates ) internal pure returns (address, uint) { uint256 minIndex = 0; // starting from 0 in case there is only one rate in array for (uint256 i=0; i<_rates.length; i++) { if (_rates[i] < _rates[minIndex]) { minIndex = i; } } return (_wrappers[minIndex], _rates[minIndex]); } function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeHelper { using SafeERC20 for ERC20; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDRESS = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; address public constant SAVER_EXCHANGE_REGISTRY = 0x25dd3F51e0C3c3Ff164DDC02A8E4D65Bb9cBB12D; address public constant ERC20_PROXY_0X = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF; address public constant ZRX_ALLOWLIST_ADDR = 0x019739e288973F92bDD3c1d87178E206E51fd911; function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } function getBalance(address _tokenAddr) internal view returns (uint balance) { if (_tokenAddr == KYBER_ETH_ADDRESS) { balance = address(this).balance; } else { balance = ERC20(_tokenAddr).balanceOf(address(this)); } } function approve0xProxy(address _tokenAddr, uint _amount) internal { if (_tokenAddr != KYBER_ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(address(ERC20_PROXY_0X), _amount); } } function sendLeftover(address _srcAddr, address _destAddr, address payable _to) internal { // send back any leftover ether or tokens if (address(this).balance > 0) { _to.transfer(address(this).balance); } if (getBalance(_srcAddr) > 0) { ERC20(_srcAddr).safeTransfer(_to, getBalance(_srcAddr)); } if (getBalance(_destAddr) > 0) { ERC20(_destAddr).safeTransfer(_to, getBalance(_destAddr)); } } function sliceUint(bytes memory bs, uint256 start) internal pure returns (uint256) { require(bs.length >= start + 32, "slicing out of range"); uint256 x; assembly { x := mload(add(bs, add(0x20, start))) } return x; } } contract SaverExchangeRegistry is AdminAuth { mapping(address => bool) private wrappers; constructor() public { wrappers[0x880A845A85F843a5c67DB2061623c6Fc3bB4c511] = true; wrappers[0x4c9B55f2083629A1F7aDa257ae984E03096eCD25] = true; wrappers[0x42A9237b872368E1bec4Ca8D26A928D7d39d338C] = true; } function addWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = true; } function removeWrapper(address _wrapper) public onlyOwner { wrappers[_wrapper] = false; } function isWrapper(address _wrapper) public view returns(bool) { return wrappers[_wrapper]; } } abstract contract CEtherInterface { function mint() external virtual payable; function repayBorrow() external virtual payable; } abstract contract Cat { struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [ray] uint256 lump; // Liquidation Quantity [wad] } mapping (bytes32 => Ilk) public ilks; } abstract contract CompoundOracleInterface { function getUnderlyingPrice(address cToken) external view virtual returns (uint); } abstract contract ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory); function exitMarket(address cToken) external virtual returns (uint256); function getAssetsIn(address account) external virtual view returns (address[] memory); function markets(address account) public virtual view returns (bool, uint256); function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256); function claimComp(address holder) virtual public; function oracle() public virtual view returns (address); } abstract contract DSProxyInterface { /// Truffle wont compile if this isn't commented // function execute(bytes memory _code, bytes memory _data) // public virtual // payable // returns (address, bytes32); function execute(address _target, bytes memory _data) public virtual payable returns (bytes32); function setCache(address _cacheAddr) public virtual payable returns (bool); function owner() public virtual returns (address); } abstract contract GemLike { function approve(address, uint) public virtual; function transfer(address, uint) public virtual; function transferFrom(address, address, uint) public virtual; function deposit() public virtual payable; function withdraw(uint) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint, address) public virtual view returns (uint); function ilks(uint) public virtual view returns (bytes32); function owns(uint) public virtual view returns (address); function urns(uint) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32) public virtual returns (uint); function give(uint, address) public virtual; function cdpAllow(uint, address, uint) public virtual; function urnAllow(address, uint) public virtual; function frob(uint, int, int) public virtual; function frob(uint, address, int, int) public virtual; function flux(uint, address, uint) public virtual; function move(uint, address, uint) public virtual; function exit(address, uint, address, uint) public virtual; function quit(uint, address) public virtual; function enter(address, uint) public virtual; function shift(uint, uint) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint); function ilks(bytes32) public virtual view returns (uint, uint, uint, uint, uint); function dai(address) public virtual view returns (uint); function urns(bytes32, address) public virtual view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public virtual; function hope(address) public virtual; function move(address, address, uint) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint); function gem() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint); function cash(bytes32, uint) public virtual; function free(bytes32) public virtual; function pack(uint) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual; } abstract contract PotLike { function chi() public virtual view returns (uint); function pie(address) public virtual view returns (uint); function drip() public virtual; function join(uint) public virtual; function exit(uint) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } abstract contract DssProxyActions { function daiJoin_join(address apt, address urn, uint wad) public virtual; function transfer(address gem, address dst, uint wad) public virtual; function ethJoin_join(address apt, address urn) public virtual payable; function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public virtual payable; function hope(address obj, address usr) public virtual; function nope(address obj, address usr) public virtual; function open(address manager, bytes32 ilk, address usr) public virtual returns (uint cdp); function give(address manager, uint cdp, address usr) public virtual; function giveToProxy(address proxyRegistry, address manager, uint cdp, address dst) public virtual; function cdpAllow(address manager, uint cdp, address usr, uint ok) public virtual; function urnAllow(address manager, address usr, uint ok) public virtual; function flux(address manager, uint cdp, address dst, uint wad) public virtual; function move(address manager, uint cdp, address dst, uint rad) public virtual; function frob(address manager, uint cdp, int dink, int dart) public virtual; function frob(address manager, uint cdp, address dst, int dink, int dart) public virtual; function quit(address manager, uint cdp, address dst) public virtual; function enter(address manager, address src, uint cdp) public virtual; function shift(address manager, uint cdpSrc, uint cdpOrg) public virtual; function makeGemBag(address gemJoin) public virtual returns (address bag); function lockETH(address manager, address ethJoin, uint cdp) public virtual payable; function safeLockETH(address manager, address ethJoin, uint cdp, address owner) public virtual payable; function lockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom) public virtual; function safeLockGem(address manager, address gemJoin, uint cdp, uint wad, bool transferFrom, address owner) public virtual; function freeETH(address manager, address ethJoin, uint cdp, uint wad) public virtual; function freeGem(address manager, address gemJoin, uint cdp, uint wad) public virtual; function draw(address manager, address jug, address daiJoin, uint cdp, uint wad) public virtual; function wipe(address manager, address daiJoin, uint cdp, uint wad) public virtual; function safeWipe(address manager, address daiJoin, uint cdp, uint wad, address owner) public virtual; function wipeAll(address manager, address daiJoin, uint cdp) public virtual; function safeWipeAll(address manager, address daiJoin, uint cdp, address owner) public virtual; function lockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD) public virtual payable; function openLockETHAndDraw(address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD) public virtual payable returns (uint cdp); function lockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom) public virtual; function openLockGemAndDraw(address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom) public virtual returns (uint cdp); function openLockGNTAndDraw(address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD) public virtual returns (address bag, uint cdp); function wipeAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeETH(address manager, address ethJoin, address daiJoin, uint cdp, uint wadC) public virtual; function wipeAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD) public virtual; function wipeAllAndFreeGem(address manager, address gemJoin, address daiJoin, uint cdp, uint wadC) public virtual; } abstract contract DaiJoin { function vat() public virtual returns (Vat); function dai() public virtual returns (Gem); function join(address, uint) public virtual payable; function exit(address, uint) public virtual; } abstract contract DssProxyActionsDsr { function join(address daiJoin, address pot, uint wad) virtual public; function exit(address daiJoin, address pot, uint wad) virtual public; function exitAll(address daiJoin, address pot) virtual public; } interface ERC20 { function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); function decimals() external view returns (uint256 digits); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } interface ExchangeInterface { function swapEtherToToken(uint256 _ethAmount, address _tokenAddress, uint256 _maxAmount) external payable returns (uint256, uint256); function swapTokenToEther(address _tokenAddress, uint256 _amount, uint256 _maxAmount) external returns (uint256); function swapTokenToToken(address _src, address _dest, uint256 _amount) external payable returns (uint256); function getExpectedRate(address src, address dest, uint256 srcQty) external view returns (uint256 expectedRate); } interface ExchangeInterfaceV2 { function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable returns (uint); function buy(address _srcAddr, address _destAddr, uint _destAmount) external payable returns(uint); function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); function getBuyRate(address _srcAddr, address _destAddr, uint _srcAmount) external view returns (uint); } abstract contract Faucet { function gulp(address) public virtual; } abstract contract Flipper { function bids(uint _bidId) public virtual returns (uint256, uint256, address, uint48, uint48, address, address, uint256); function tend(uint id, uint lot, uint bid) virtual external; function dent(uint id, uint lot, uint bid) virtual external; function deal(uint id) virtual external; } abstract contract GasTokenInterface is ERC20 { function free(uint256 value) public virtual returns (bool success); function freeUpTo(uint256 value) public virtual returns (uint256 freed); function freeFrom(address from, uint256 value) public virtual returns (bool success); function freeFromUpTo(address from, uint256 value) public virtual returns (uint256 freed); } abstract contract Gem { function dec() virtual public returns (uint); function gem() virtual public returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; function approve(address, uint) virtual public; function transfer(address, uint) virtual public returns (bool); function transferFrom(address, address, uint) virtual public returns (bool); function deposit() virtual public payable; function withdraw(uint) virtual public; function allowance(address, address) virtual public returns (uint); } abstract contract GetCdps { function getCdpsAsc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); function getCdpsDesc(address manager, address guy) external view virtual returns (uint[] memory ids, address[] memory urns, bytes32[] memory ilks); } abstract contract IAToken { function redeem(uint256 _amount) external virtual; } abstract contract IAaveSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ICompoundSubscription { function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) public virtual; function unsubscribe() public virtual; } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external virtual payable; function setUserUseReserveAsCollateral(address _reserve, bool _useAsCollateral) external virtual; function borrow(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external virtual; function repay( address _reserve, uint256 _amount, address payable _onBehalfOf) external virtual payable; function swapBorrowRateMode(address _reserve) external virtual; function getReserves() external virtual view returns(address[] memory); /// @param _reserve underlying token address function getReserveData(address _reserve) external virtual view returns ( uint256 totalLiquidity, // reserve total liquidity uint256 availableLiquidity, // reserve available liquidity for borrowing uint256 totalBorrowsStable, // total amount of outstanding borrows at Stable rate uint256 totalBorrowsVariable, // total amount of outstanding borrows at Variable rate uint256 liquidityRate, // current deposit APY of the reserve for depositors, in Ray units. uint256 variableBorrowRate, // current variable rate APY of the reserve pool, in Ray units. uint256 stableBorrowRate, // current stable rate APY of the reserve pool, in Ray units. uint256 averageStableBorrowRate, // current average stable borrow rate uint256 utilizationRate, // expressed as total borrows/total liquidity. uint256 liquidityIndex, // cumulative liquidity index uint256 variableBorrowIndex, // cumulative variable borrow index address aTokenAddress, // aTokens contract address for the specific _reserve uint40 lastUpdateTimestamp // timestamp of the last update of reserve data ); /// @param _user users address function getUserAccountData(address _user) external virtual view returns ( uint256 totalLiquidityETH, // user aggregated deposits across all the reserves. In Wei uint256 totalCollateralETH, // user aggregated collateral across all the reserves. In Wei uint256 totalBorrowsETH, // user aggregated outstanding borrows across all the reserves. In Wei uint256 totalFeesETH, // user aggregated current outstanding fees in ETH. In Wei uint256 availableBorrowsETH, // user available amount to borrow in ETH uint256 currentLiquidationThreshold, // user current average liquidation threshold across all the collaterals deposited uint256 ltv, // user average Loan-to-Value between all the collaterals uint256 healthFactor // user current Health Factor ); /// @param _reserve underlying token address /// @param _user users address function getUserReserveData(address _reserve, address _user) external virtual view returns ( uint256 currentATokenBalance, // user current reserve aToken balance uint256 currentBorrowBalance, // user current reserve outstanding borrow balance uint256 principalBorrowBalance, // user balance of borrowed asset uint256 borrowRateMode, // user borrow rate mode either Stable or Variable uint256 borrowRate, // user current borrow rate APY uint256 liquidityRate, // user current earn rate on _reserve uint256 originationFee, // user outstanding loan origination fee uint256 variableBorrowIndex, // user variable cumulative index uint256 lastUpdateTimestamp, // Timestamp of the last data update bool usageAsCollateralEnabled // Whether the user's current reserve is enabled as a collateral ); function getReserveConfigurationData(address _reserve) external virtual view returns ( uint256 ltv, uint256 liquidationThreshold, uint256 liquidationBonus, address rateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool stableBorrowRateEnabled, bool isActive ); // ------------------ LendingPoolCoreData ------------------------ function getReserveATokenAddress(address _reserve) public virtual view returns (address); function getReserveConfiguration(address _reserve) external virtual view returns (uint256, uint256, uint256, bool); function getUserUnderlyingAssetBalance(address _reserve, address _user) public virtual view returns (uint256); function getReserveCurrentLiquidityRate(address _reserve) public virtual view returns (uint256); function getReserveCurrentVariableBorrowRate(address _reserve) public virtual view returns (uint256); function getReserveTotalLiquidity(address _reserve) public virtual view returns (uint256); function getReserveAvailableLiquidity(address _reserve) public virtual view returns (uint256); function getReserveTotalBorrowsVariable(address _reserve) public virtual view returns (uint256); // ---------------- LendingPoolDataProvider --------------------- function calculateUserGlobalData(address _user) public virtual view returns ( uint256 totalLiquidityBalanceETH, uint256 totalCollateralBalanceETH, uint256 totalBorrowBalanceETH, uint256 totalFeesETH, uint256 currentLtv, uint256 currentLiquidationThreshold, uint256 healthFactor, bool healthFactorBelowThreshold ); } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public virtual view returns (address); function getLendingPoolCore() public virtual view returns (address payable); function getLendingPoolConfigurator() public virtual view returns (address); function getLendingPoolDataProvider() public virtual view returns (address); function getLendingPoolParametersProvider() public virtual view returns (address); function getTokenDistributor() public virtual view returns (address); function getFeeProvider() public virtual view returns (address); function getLendingPoolLiquidationManager() public virtual view returns (address); function getLendingPoolManager() public virtual view returns (address); function getPriceOracle() public virtual view returns (address); function getLendingRateOracle() public virtual view returns (address); } abstract contract ILoanShifter { function getLoanAmount(uint, address) public view virtual returns(uint); function getUnderlyingAsset(address _addr) public view virtual returns (address); } abstract contract IPriceOracleGetterAave { function getAssetPrice(address _asset) external virtual view returns (uint256); function getAssetsPrices(address[] calldata _assets) external virtual view returns(uint256[] memory); function getSourceOfAsset(address _asset) external virtual view returns(address); function getFallbackOracle() external virtual view returns(address); } abstract contract ITokenInterface is ERC20 { function assetBalanceOf(address _owner) public virtual view returns (uint256); function mint(address receiver, uint256 depositAmount) external virtual returns (uint256 mintAmount); function burn(address receiver, uint256 burnAmount) external virtual returns (uint256 loanAmountPaid); function tokenPrice() public virtual view returns (uint256 price); } abstract contract Join { bytes32 public ilk; function dec() virtual public view returns (uint); function gem() virtual public view returns (Gem); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract Jug { struct Ilk { uint256 duty; uint256 rho; } mapping (bytes32 => Ilk) public ilks; function drip(bytes32) public virtual returns (uint); } abstract contract KyberNetworkProxyInterface { function maxGasPrice() external virtual view returns (uint256); function getUserCapInWei(address user) external virtual view returns (uint256); function getUserCapInTokenWei(address user, ERC20 token) external virtual view returns (uint256); function enabled() external virtual view returns (bool); function info(bytes32 id) external virtual view returns (uint256); function getExpectedRate(ERC20 src, ERC20 dest, uint256 srcQty) public virtual view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes memory hint ) public virtual payable returns (uint256); function trade( ERC20 src, uint256 srcAmount, ERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId ) public virtual payable returns (uint256); function swapEtherToToken(ERC20 token, uint256 minConversionRate) external virtual payable returns (uint256); function swapTokenToEther(ERC20 token, uint256 tokenQty, uint256 minRate) external virtual payable returns (uint256); function swapTokenToToken(ERC20 src, uint256 srcAmount, ERC20 dest, uint256 minConversionRate) public virtual returns (uint256); } abstract contract Manager { function last(address) virtual public returns (uint); function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract OasisInterface { function getBuyAmount(address tokenToBuy, address tokenToPay, uint256 amountToPay) external virtual view returns (uint256 amountBought); function getPayAmount(address tokenToPay, address tokenToBuy, uint256 amountToBuy) public virtual view returns (uint256 amountPaid); function sellAllAmount(address pay_gem, uint256 pay_amt, address buy_gem, uint256 min_fill_amount) public virtual returns (uint256 fill_amt); function buyAllAmount(address buy_gem, uint256 buy_amt, address pay_gem, uint256 max_fill_amount) public virtual returns (uint256 fill_amt); } abstract contract Osm { mapping(address => uint256) public bud; function peep() external view virtual returns (bytes32, bool); } abstract contract OsmMom { mapping (bytes32 => address) public osms; } abstract contract OtcInterface { function buyAllAmount(address, uint256, address, uint256) public virtual returns (uint256); function getPayAmount(address, address, uint256) public virtual view returns (uint256); function getBuyAmount(address, address, uint256) public virtual view returns (uint256); } abstract contract PipInterface { function read() public virtual returns (bytes32); } abstract contract ProxyRegistryInterface { function proxies(address _owner) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract SaverExchangeInterface { function getBestPrice( uint256 _amount, address _srcToken, address _destToken, uint256 _exchangeType ) public view virtual returns (address, uint256); } abstract contract Spotter { struct Ilk { PipInterface pip; uint256 mat; } mapping (bytes32 => Ilk) public ilks; uint256 public par; } abstract contract TokenInterface { function allowance(address, address) public virtual returns (uint256); function balanceOf(address) public virtual returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom(address, address, uint256) public virtual returns (bool); function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract UniswapExchangeInterface { function getEthToTokenInputPrice(uint256 eth_sold) external virtual view returns (uint256 tokens_bought); function getEthToTokenOutputPrice(uint256 tokens_bought) external virtual view returns (uint256 eth_sold); function getTokenToEthInputPrice(uint256 tokens_sold) external virtual view returns (uint256 eth_bought); function getTokenToEthOutputPrice(uint256 eth_bought) external virtual view returns (uint256 tokens_sold); function tokenToEthTransferInput( uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient ) external virtual returns (uint256 eth_bought); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external virtual payable returns (uint256 tokens_bought); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_bought); function ethToTokenTransferOutput( uint256 tokens_bought, uint256 deadline, address recipient ) external virtual payable returns (uint256 eth_sold); function tokenToEthTransferOutput( uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient ) external virtual returns (uint256 tokens_sold); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr ) external virtual returns (uint256 tokens_sold); } abstract contract UniswapFactoryInterface { function getExchange(address token) external view virtual returns (address exchange); } abstract contract UniswapRouterInterface { function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual returns (uint[] memory amounts); function getAmountsOut(uint amountIn, address[] memory path) public virtual view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] memory path) public virtual view returns (uint[] memory amounts); } abstract contract Vat { struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] function can(address, address) virtual public view returns (uint); function dai(address) virtual public view returns (uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; function fork(bytes32, address, address, int, int) virtual public; } contract DefisaverLogger { event LogEvent( address indexed contractAddress, address indexed caller, string indexed logName, bytes data ); // solhint-disable-next-line func-name-mixedcase function Log(address _contract, address _caller, string memory _logName, bytes memory _data) public { emit LogEvent(_contract, _caller, _logName, _data); } } contract MCDMonitorProxyV2 is AdminAuth { uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _saverProxy Address of MCDSaverProxy /// @param _data Data to send to MCDSaverProxy function callExecute(address _owner, address _saverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_saverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract MCDPriceVerifier is AdminAuth { OsmMom public osmMom = OsmMom(0x76416A4d5190d071bfed309861527431304aA14f); Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); mapping(address => bool) public authorized; function verifyVaultNextPrice(uint _nextPrice, uint _cdpId) public view returns(bool) { require(authorized[msg.sender]); bytes32 ilk = manager.ilks(_cdpId); return verifyNextPrice(_nextPrice, ilk); } function verifyNextPrice(uint _nextPrice, bytes32 _ilk) public view returns(bool) { require(authorized[msg.sender]); address osmAddress = osmMom.osms(_ilk); uint whitelisted = Osm(osmAddress).bud(address(this)); // If contracts doesn't have access return true if (whitelisted != 1) return true; (bytes32 price, bool has) = Osm(osmAddress).peep(); return has ? uint(price) == _nextPrice : false; } function setAuthorized(address _address, bool _allowed) public onlyOwner { authorized[_address] = _allowed; } } abstract contract StaticV2 { enum Method { Boost, Repay } struct CdpHolder { uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; address owner; uint cdpId; bool boostEnabled; bool nextPriceEnabled; } struct SubPosition { uint arrPos; bool subscribed; } } contract SubscriptionsInterfaceV2 { function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external {} function unsubscribe(uint _cdpId) external {} } contract SubscriptionsProxyV2 { address public constant MONITOR_PROXY_ADDRESS = 0x7456f4218874eAe1aF8B83a64848A1B89fEB7d7C; address public constant OLD_SUBSCRIPTION = 0x83152CAA0d344a2Fd428769529e2d490A88f4393; address public constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; function migrate(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(OLD_SUBSCRIPTION).unsubscribe(_cdpId); subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled, _subscriptions); } function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { address currAuthority = address(DSAuth(address(this)).authority()); DSGuard guard = DSGuard(currAuthority); if (currAuthority == address(0)) { guard = DSGuardFactory(FACTORY_ADDRESS).newGuard(); DSAuth(address(this)).setAuthority(DSAuthority(address(guard))); } guard.permit(MONITOR_PROXY_ADDRESS, address(this), bytes4(keccak256("execute(address,bytes)"))); SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function update(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled, bool _nextPriceEnabled, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).subscribe(_cdpId, _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled, _nextPriceEnabled); } function unsubscribe(uint _cdpId, address _subscriptions) public { SubscriptionsInterfaceV2(_subscriptions).unsubscribe(_cdpId); } } contract SubscriptionsV2 is AdminAuth, StaticV2 { bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; bytes32 internal constant BAT_ILK = 0x4241542d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; CdpHolder[] public subscribers; mapping (uint => SubPosition) public subscribersPos; mapping (bytes32 => uint) public minLimits; uint public changeIndex; Manager public manager = Manager(MANAGER_ADDRESS); Vat public vat = Vat(VAT_ADDRESS); Spotter public spotter = Spotter(SPOTTER_ADDRESS); MCDSaverProxy public saverProxy; event Subscribed(address indexed owner, uint cdpId); event Unsubscribed(address indexed owner, uint cdpId); event Updated(address indexed owner, uint cdpId); event ParamUpdates(address indexed owner, uint cdpId, uint128, uint128, uint128, uint128, bool boostEnabled); /// @param _saverProxy Address of the MCDSaverProxy contract constructor(address _saverProxy) public { saverProxy = MCDSaverProxy(payable(_saverProxy)); minLimits[ETH_ILK] = 1700000000000000000; minLimits[BAT_ILK] = 1700000000000000000; } /// @dev Called by the DSProxy contract which owns the CDP /// @notice Adds the users CDP in the list of subscriptions so it can be monitored /// @param _cdpId Id of the CDP /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled /// @param _nextPriceEnabled Boolean determing if we can use nextPrice for this cdp function subscribe(uint _cdpId, uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled, bool _nextPriceEnabled) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(manager.ilks(_cdpId), _minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[_cdpId]; CdpHolder memory subscription = CdpHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, owner: msg.sender, cdpId: _cdpId, boostEnabled: _boostEnabled, nextPriceEnabled: _nextPriceEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender, _cdpId); emit ParamUpdates(msg.sender, _cdpId, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender, _cdpId); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe(uint _cdpId) external { require(isOwner(msg.sender, _cdpId), "Must be called by Cdp owner"); _unsubscribe(_cdpId); } /// @dev Checks if the _owner is the owner of the CDP function isOwner(address _owner, uint _cdpId) internal view returns (bool) { return getOwner(_cdpId) == _owner; } /// @dev Checks limit for minimum ratio and if minRatio is bigger than max function checkParams(bytes32 _ilk, uint128 _minRatio, uint128 _maxRatio) internal view returns (bool) { if (_minRatio < minLimits[_ilk]) { return false; } if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list function _unsubscribe(uint _cdpId) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_cdpId]; require(subInfo.subscribed, "Must first be subscribed"); uint lastCdpId = subscribers[subscribers.length - 1].cdpId; SubPosition storage subInfo2 = subscribersPos[lastCdpId]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender, _cdpId); } /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Helper method for the front to get all the info about the subscribed CDP function getSubscribedInfo(uint _cdpId) public view returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, 0, 0, 0, 0, address(0), 0, 0); (coll, debt) = saverProxy.getCdpInfo(manager, _cdpId, manager.ilks(_cdpId)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return ( true, subscriber.minRatio, subscriber.maxRatio, subscriber.optimalRatioRepay, subscriber.optimalRatioBoost, subscriber.owner, coll, debt ); } function getCdpHolder(uint _cdpId) public view returns (bool subscribed, CdpHolder memory) { SubPosition memory subInfo = subscribersPos[_cdpId]; if (!subInfo.subscribed) return (false, CdpHolder(0, 0, 0, 0, address(0), 0, false, false)); CdpHolder memory subscriber = subscribers[subInfo.arrPos]; return (true, subscriber); } /// @notice Helper method for the front to get the information about the ilk of a CDP function getIlkInfo(bytes32 _ilk, uint _cdpId) public view returns(bytes32 ilk, uint art, uint rate, uint spot, uint line, uint dust, uint mat, uint par) { // send either ilk or cdpId if (_ilk == bytes32(0)) { _ilk = manager.ilks(_cdpId); } ilk = _ilk; (,mat) = spotter.ilks(_ilk); par = spotter.par(); (art, rate, spot, line, dust) = vat.ilks(_ilk); } /// @notice Helper method to return all the subscribed CDPs function getSubscribers() public view returns (CdpHolder[] memory) { return subscribers; } /// @notice Helper method to return all the subscribed CDPs function getSubscribersByPage(uint _page, uint _perPage) public view returns (CdpHolder[] memory) { CdpHolder[] memory holders = new CdpHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; uint count = 0; for (uint i=start; i<end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to change a min. limit for an asset function changeMinRatios(bytes32 _ilk, uint _newRatio) public onlyOwner { minLimits[_ilk] = _newRatio; } /// @notice Admin function to unsubscribe a CDP function unsubscribeByAdmin(uint _cdpId) public onlyOwner { SubPosition storage subInfo = subscribersPos[_cdpId]; if (subInfo.subscribed) { _unsubscribe(_cdpId); } } } contract BidProxy { address public constant DAI_JOIN = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function daiBid(uint _bidId, uint _amount, address _flipper) public { uint tendAmount = _amount * (10 ** 27); joinDai(_amount); (, uint lot, , , , , , ) = Flipper(_flipper).bids(_bidId); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).tend(_bidId, lot, tendAmount); } function collateralBid(uint _bidId, uint _amount, address _flipper) public { (uint bid, , , , , , , ) = Flipper(_flipper).bids(_bidId); joinDai(bid / (10**27)); Vat(VAT_ADDRESS).hope(_flipper); Flipper(_flipper).dent(_bidId, _amount, bid); } function closeBid(uint _bidId, address _flipper, address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); Flipper(_flipper).deal(_bidId); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitCollateral(address _joinAddr) public { bytes32 ilk = Join(_joinAddr).ilk(); uint amount = Vat(VAT_ADDRESS).gem(ilk, address(this)) / (10**27); Vat(VAT_ADDRESS).hope(_joinAddr); Gem(_joinAddr).exit(msg.sender, amount); } function exitDai() public { uint amount = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); Vat(VAT_ADDRESS).hope(DAI_JOIN); Gem(DAI_JOIN).exit(msg.sender, amount); } function withdrawToken(address _token) public { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, balance); } function withdrawEth() public { uint balance = address(this).balance; msg.sender.transfer(balance); } function joinDai(uint _amount) internal { uint amountInVat = Vat(VAT_ADDRESS).dai(address(this)) / (10**27); if (_amount > amountInVat) { uint amountDiff = (_amount - amountInVat) + 1; ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), amountDiff); ERC20(DAI_ADDRESS).approve(DAI_JOIN, amountDiff); Join(DAI_JOIN).join(address(this), amountDiff); } } } abstract contract IMCDSubscriptions { function unsubscribe(uint256 _cdpId) external virtual ; function subscribersPos(uint256 _cdpId) external virtual returns (uint256, bool); } abstract contract GemLike { function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual; function transferFrom(address, address, uint256) public virtual; function deposit() public virtual payable; function withdraw(uint256) public virtual; } abstract contract ManagerLike { function cdpCan(address, uint256, address) public virtual view returns (uint256); function ilks(uint256) public virtual view returns (bytes32); function owns(uint256) public virtual view returns (address); function urns(uint256) public virtual view returns (address); function vat() public virtual view returns (address); function open(bytes32, address) public virtual returns (uint256); function give(uint256, address) public virtual; function cdpAllow(uint256, address, uint256) public virtual; function urnAllow(address, uint256) public virtual; function frob(uint256, int256, int256) public virtual; function flux(uint256, address, uint256) public virtual; function move(uint256, address, uint256) public virtual; function exit(address, uint256, address, uint256) public virtual; function quit(uint256, address) public virtual; function enter(address, uint256) public virtual; function shift(uint256, uint256) public virtual; } abstract contract VatLike { function can(address, address) public virtual view returns (uint256); function ilks(bytes32) public virtual view returns (uint256, uint256, uint256, uint256, uint256); function dai(address) public virtual view returns (uint256); function urns(bytes32, address) public virtual view returns (uint256, uint256); function frob(bytes32, address, address, address, int256, int256) public virtual; function hope(address) public virtual; function move(address, address, uint256) public virtual; } abstract contract GemJoinLike { function dec() public virtual returns (uint256); function gem() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract GNTJoinLike { function bags(address) public virtual view returns (address); function make(address) public virtual returns (address); } abstract contract DaiJoinLike { function vat() public virtual returns (VatLike); function dai() public virtual returns (GemLike); function join(address, uint256) public virtual payable; function exit(address, uint256) public virtual; } abstract contract HopeLike { function hope(address) public virtual; function nope(address) public virtual; } abstract contract ProxyRegistryInterface { function build(address) public virtual returns (address); } abstract contract EndLike { function fix(bytes32) public virtual view returns (uint256); function cash(bytes32, uint256) public virtual; function free(bytes32) public virtual; function pack(uint256) public virtual; function skim(bytes32, address) public virtual; } abstract contract JugLike { function drip(bytes32) public virtual returns (uint256); } abstract contract PotLike { function pie(address) public virtual view returns (uint256); function drip() public virtual returns (uint256); function join(uint256) public virtual; function exit(uint256) public virtual; } abstract contract ProxyRegistryLike { function proxies(address) public virtual view returns (address); function build(address) public virtual returns (address); } abstract contract ProxyLike { function owner() public virtual view returns (address); } contract Common { uint256 constant RAY = 10**27; // Internal functions function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions // solhint-disable-next-line func-name-mixedcase function daiJoin_join(address apt, address urn, uint256 wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract MCDCreateProxyActions is Common { // Internal functions function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint256 x) internal pure returns (int256 y) { y = int256(x); require(y >= 0, "int-overflow"); } function toRad(uint256 wad) internal pure returns (uint256 rad) { rad = mul(wad, 10**27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul(amt, 10**(18 - GemJoinLike(gemJoin).dec())); } function _getDrawDart(address vat, address jug, address urn, bytes32 ilk, uint256 wad) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint256(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart(address vat, uint256 dai, address urn, bytes32 ilk) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -toInt(art); } function _getWipeAllWad(address vat, address usr, address urn, bytes32 ilk) internal view returns (uint256 wad) { // Gets actual rate from the vat (, uint256 rate, , , ) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint256 art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint256 dai = VatLike(vat).dai(usr); uint256 rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint256 wad) public { GemLike(gem).transfer(dst, wad); } // solhint-disable-next-line func-name-mixedcase function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } // solhint-disable-next-line func-name-mixedcase function gemJoin_join(address apt, address urn, uint256 wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope(address obj, address usr) public { HopeLike(obj).hope(usr); } function nope(address obj, address usr) public { HopeLike(obj).nope(usr); } function open(address manager, bytes32 ilk, address usr) public returns (uint256 cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give(address manager, uint256 cdp, address usr) public { ManagerLike(manager).give(cdp, usr); } function move(address manager, uint256 cdp, address dst, uint256 rad) public { ManagerLike(manager).move(cdp, dst, rad); } function frob(address manager, uint256 cdp, int256 dink, int256 dart) public { ManagerLike(manager).frob(cdp, dink, dart); } function lockETH(address manager, address ethJoin, uint256 cdp) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function lockGem(address manager, address gemJoin, uint256 cdp, uint256 wad, bool transferFrom) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); } function draw(address manager, address jug, address daiJoin, uint256 cdp, uint256 wad) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint256 cdp, uint256 wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint256 wadD, address owner ) public payable returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); give(manager, cdp, owner); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint256 cdp, uint256 wadC, uint256 wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob( manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD) ); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint256 wadC, uint256 wadD, bool transferFrom, address owner ) public returns (uint256 cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); give(manager, cdp, owner); } } contract MCDCreateTaker { address payable public constant MCD_CREATE_FLASH_LOAN = 0x71eC9a4fCE561c3936a511D9ebb05B60CF2bA519; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); struct CreateData { uint collAmount; uint daiAmount; address joinAddr; } function openWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CreateData memory _createData ) public payable { MCD_CREATE_FLASH_LOAN.transfer(msg.value); //0x fee if (_createData.joinAddr != ETH_JOIN_ADDRESS) { ERC20(getCollateralAddr(_createData.joinAddr)).transferFrom(msg.sender, address(this), _createData.collAmount); ERC20(getCollateralAddr(_createData.joinAddr)).transfer(MCD_CREATE_FLASH_LOAN, _createData.collAmount); } (uint[6] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_createData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this)); lendingPool.flashLoan(MCD_CREATE_FLASH_LOAN, DAI_ADDRESS, _createData.daiAmount, paramsData); logger.Log(address(this), msg.sender, "MCDCreate", abi.encode(manager.last(address(this)), _createData.collAmount, _createData.daiAmount)); } function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } function _packData( CreateData memory _createData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _createData.collAmount, _createData.daiAmount, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _createData.joinAddr ]; callData = exchangeData.callData; } } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract ManagerLike { function cdpCan(address, uint, address) virtual public view returns (uint); function ilks(uint) virtual public view returns (bytes32); function owns(uint) virtual public view returns (address); function urns(uint) virtual public view returns (address); function vat() virtual public view returns (address); function open(bytes32, address) virtual public returns (uint); function give(uint, address) virtual public; function cdpAllow(uint, address, uint) virtual public; function urnAllow(address, uint) virtual public; function frob(uint, int, int) virtual public; function flux(uint, address, uint) virtual public; function move(uint, address, uint) virtual public; function exit(address, uint, address, uint) virtual public; function quit(uint, address) virtual public; function enter(address, uint) virtual public; function shift(uint, uint) virtual public; } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract GemJoinLike { function dec() virtual public returns (uint); function gem() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract GNTJoinLike { function bags(address) virtual public view returns (address); function make(address) virtual public returns (address); } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } abstract contract HopeLike { function hope(address) virtual public; function nope(address) virtual public; } abstract contract ProxyRegistryInterface { function proxies(address _owner) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract EndLike { function fix(bytes32) virtual public view returns (uint); function cash(bytes32, uint) virtual public; function free(bytes32) virtual public; function pack(uint) virtual public; function skim(bytes32, address) virtual public; } abstract contract JugLike { function drip(bytes32) virtual public returns (uint); } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract ProxyRegistryLike { function proxies(address) virtual public view returns (address); function build(address) virtual public returns (address); } abstract contract ProxyLike { function owner() virtual public view returns (address); } abstract contract DSProxy { function execute(address _target, bytes memory _data) virtual public payable returns (bytes32); function setOwner(address owner_) virtual public; } contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract SaverProxyActions is Common { event CDPAction(string indexed, uint indexed, uint, uint); // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint wad) public { GemLike(gem).transfer(dst, wad); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value: msg.value}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint wad, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, wad); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, wad); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); emit CDPAction('give', cdp, 0, 0); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); emit CDPAction('lockETH', cdp, msg.value, 0); } function lockGem( address manager, address gemJoin, uint cdp, uint wad, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), wad, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, wad)), 0 ); emit CDPAction('lockGem', cdp, wad, 0); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); emit CDPAction('freeETH', cdp, wad, 0); } function freeGem( address manager, address gemJoin, uint cdp, uint wad ) public { uint wad18 = convertTo18(gemJoin, wad); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad18), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); emit CDPAction('freeGem', cdp, wad, 0); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, wad)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wad); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); emit CDPAction('draw', cdp, 0, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } emit CDPAction('wipe', cdp, 0, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } emit CDPAction('wipeAll', cdp, 0, art); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); emit CDPAction('openLockETHAndDraw', cdp, msg.value, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, wadC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, wadC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, wadC, wadD, transferFrom); emit CDPAction('openLockGemAndDraw', cdp, wadC, wadD); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); emit CDPAction('wipeAllAndFreeETH', cdp, wadC, art); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wad18 = convertTo18(gemJoin, wadC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wad18), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad18); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, wadC); emit CDPAction('wipeAllAndFreeGem', cdp, wadC, art); } function createProxyAndCDP( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD, address registry ) public payable returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockETHAndDraw(manager, jug, ethJoin, daiJoin, ilk, wadD ); give(manager, cdp, address(proxy)); return cdp; } function createProxyAndGemCDP( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint wadC, uint wadD, bool transferFrom, address registry ) public returns(uint) { address proxy = ProxyRegistryInterface(registry).build(msg.sender); uint cdp = openLockGemAndDraw(manager, jug, gemJoin, daiJoin, ilk, wadC, wadD, transferFrom); give(manager, cdp, address(proxy)); return cdp; } } contract MCDSaverProxyHelper is DSMath { /// @notice Returns a normalized debt _amount based on the current rate /// @param _amount Amount of dai to be normalized /// @param _rate Current rate of the stability fee /// @param _daiVatBalance Balance od Dai in the Vat for that CDP function normalizeDrawAmount(uint _amount, uint _rate, uint _daiVatBalance) internal pure returns (int dart) { if (_daiVatBalance < mul(_amount, RAY)) { dart = toPositiveInt(sub(mul(_amount, RAY), _daiVatBalance) / _rate); dart = mul(uint(dart), _rate) < mul(_amount, RAY) ? dart + 1 : dart; } } /// @notice Converts a number to Rad percision /// @param _wad The input number in wad percision function toRad(uint _wad) internal pure returns (uint) { return mul(_wad, 10 ** 27); } /// @notice Converts a number to 18 decimal percision /// @param _joinAddr Join address of the collateral /// @param _amount Number to be converted function convertTo18(address _joinAddr, uint256 _amount) internal view returns (uint256) { return mul(_amount, 10 ** (18 - Join(_joinAddr).dec())); } /// @notice Converts a uint to int and checks if positive /// @param _x Number to be converted function toPositiveInt(uint _x) internal pure returns (int y) { y = int(_x); require(y >= 0, "int-overflow"); } /// @notice Gets Dai amount in Vat which can be added to Cdp /// @param _vat Address of Vat contract /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function normalizePaybackAmount(address _vat, address _urn, bytes32 _ilk) internal view returns (int amount) { uint dai = Vat(_vat).dai(_urn); (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); amount = toPositiveInt(dai / rate); amount = uint(amount) <= art ? - amount : - toPositiveInt(art); } /// @notice Gets the whole debt of the CDP /// @param _vat Address of Vat contract /// @param _usr Address of the Dai holder /// @param _urn Urn of the Cdp /// @param _ilk Ilk of the Cdp function getAllDebt(address _vat, address _usr, address _urn, bytes32 _ilk) internal view returns (uint daiAmount) { (, uint rate,,,) = Vat(_vat).ilks(_ilk); (, uint art) = Vat(_vat).urns(_ilk, _urn); uint dai = Vat(_vat).dai(_usr); uint rad = sub(mul(art, rate), dai); daiAmount = rad / RAY; daiAmount = mul(daiAmount, RAY) < rad ? daiAmount + 1 : daiAmount; } /// @notice Gets the token address from the Join contract /// @param _joinAddr Address of the Join contract function getCollateralAddr(address _joinAddr) internal view returns (address) { return address(Join(_joinAddr).gem()); } /// @notice Gets CDP info (collateral, debt) /// @param _manager Manager contract /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(Manager _manager, uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address vat = _manager.vat(); address urn = _manager.urns(_cdpId); (uint collateral, uint debt) = Vat(vat).urns(_ilk, urn); (,uint rate,,,) = Vat(vat).ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Address that owns the DSProxy that owns the CDP /// @param _manager Manager contract /// @param _cdpId Id of the CDP function getOwner(Manager _manager, uint _cdpId) public view returns (address) { DSProxy proxy = DSProxy(uint160(_manager.owns(_cdpId))); return proxy.owner(); } } abstract contract ILendingPool { function flashLoan( address payable _receiver, address _reserve, uint _amount, bytes calldata _params) external virtual; } abstract contract ProtocolInterface { function deposit(address _user, uint256 _amount) public virtual; function withdraw(address _user, uint256 _amount) public virtual; } contract SavingsLogger { event Deposit(address indexed sender, uint8 protocol, uint256 amount); event Withdraw(address indexed sender, uint8 protocol, uint256 amount); event Swap(address indexed sender, uint8 fromProtocol, uint8 toProtocol, uint256 amount); function logDeposit(address _sender, uint8 _protocol, uint256 _amount) external { emit Deposit(_sender, _protocol, _amount); } function logWithdraw(address _sender, uint8 _protocol, uint256 _amount) external { emit Withdraw(_sender, _protocol, _amount); } function logSwap(address _sender, uint8 _protocolFrom, uint8 _protocolTo, uint256 _amount) external { emit Swap(_sender, _protocolFrom, _protocolTo, _amount); } } contract AaveSavingsProtocol is ProtocolInterface, DSAuth { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant AAVE_LENDING_POOL = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119; address public constant AAVE_LENDING_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); ERC20(DAI_ADDRESS).approve(AAVE_LENDING_POOL_CORE, uint(-1)); ILendingPool(AAVE_LENDING_POOL).deposit(DAI_ADDRESS, _amount, 0); ERC20(ADAI_ADDRESS).transfer(_user, ERC20(ADAI_ADDRESS).balanceOf(address(this))); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); require(ERC20(ADAI_ADDRESS).transferFrom(_user, address(this), _amount)); IAToken(ADAI_ADDRESS).redeem(_amount); // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } contract CompoundSavingsProtocol { address public constant NEW_CDAI_ADDRESS = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; CTokenInterface public constant cDaiContract = CTokenInterface(NEW_CDAI_ADDRESS); function compDeposit(address _user, uint _amount) internal { // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // mainnet only ERC20(DAI_ADDRESS).approve(NEW_CDAI_ADDRESS, uint(-1)); // mint cDai require(cDaiContract.mint(_amount) == 0, "Failed Mint"); } function compWithdraw(address _user, uint _amount) internal { // transfer all users balance to this contract require(cDaiContract.transferFrom(_user, address(this), ERC20(NEW_CDAI_ADDRESS).balanceOf(_user))); // approve cDai to compound contract cDaiContract.approve(NEW_CDAI_ADDRESS, uint(-1)); // get dai from cDai contract require(cDaiContract.redeemUnderlying(_amount) == 0, "Reedem Failed"); // return to user balance we didn't spend uint cDaiBalance = cDaiContract.balanceOf(address(this)); if (cDaiBalance > 0) { cDaiContract.transfer(_user, cDaiBalance); } // return dai we have to user ERC20(DAI_ADDRESS).transfer(_user, _amount); } } abstract contract VatLike { function can(address, address) virtual public view returns (uint); function ilks(bytes32) virtual public view returns (uint, uint, uint, uint, uint); function dai(address) virtual public view returns (uint); function urns(bytes32, address) virtual public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) virtual public; function hope(address) virtual public; function move(address, address, uint) virtual public; } abstract contract PotLike { function pie(address) virtual public view returns (uint); function drip() virtual public returns (uint); function join(uint) virtual public; function exit(uint) virtual public; } abstract contract GemLike { function approve(address, uint) virtual public; function transfer(address, uint) virtual public; function transferFrom(address, address, uint) virtual public; function deposit() virtual public payable; function withdraw(uint) virtual public; } abstract contract DaiJoinLike { function vat() virtual public returns (VatLike); function dai() virtual public returns (GemLike); function join(address, uint) virtual public payable; function exit(address, uint) virtual public; } contract DSRSavingsProtocol is DSMath { // Mainnet address public constant POT_ADDRESS = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; function dsrDeposit(uint _amount, bool _fromUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); daiJoin_join(DAI_JOIN_ADDRESS, address(this), _amount, _fromUser); if (vat.can(address(this), address(POT_ADDRESS)) == 0) { vat.hope(POT_ADDRESS); } PotLike(POT_ADDRESS).join(mul(_amount, RAY) / chi); } function dsrWithdraw(uint _amount, bool _toUser) internal { VatLike vat = DaiJoinLike(DAI_JOIN_ADDRESS).vat(); uint chi = PotLike(POT_ADDRESS).drip(); uint pie = mul(_amount, RAY) / chi; PotLike(POT_ADDRESS).exit(pie); uint balance = DaiJoinLike(DAI_JOIN_ADDRESS).vat().dai(address(this)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } address to; if (_toUser) { to = msg.sender; } else { to = address(this); } if (_amount == uint(-1)) { DaiJoinLike(DAI_JOIN_ADDRESS).exit(to, mul(chi, pie) / RAY); } else { DaiJoinLike(DAI_JOIN_ADDRESS).exit( to, balance >= mul(_amount, RAY) ? _amount : balance / RAY ); } } function daiJoin_join(address apt, address urn, uint wad, bool _fromUser) internal { if (_fromUser) { DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); } DaiJoinLike(apt).dai().approve(apt, wad); DaiJoinLike(apt).join(urn, wad); } } contract DydxSavingsProtocol is ProtocolInterface, DSAuth { address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; ISoloMargin public soloMargin; address public savingsProxy; uint daiMarketId = 3; constructor() public { soloMargin = ISoloMargin(SOLO_MARGIN_ADDRESS); } function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); Account.Info[] memory accounts = new Account.Info[](1); accounts[0] = getAccount(_user, 0); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1); Types.AssetAmount memory amount = Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: _amount }); actions[0] = Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: amount, primaryMarketId: daiMarketId, otherAddress: _user, secondaryMarketId: 0, //not used otherAccountId: 0, //not used data: "" //not used }); soloMargin.operate(accounts, actions); } function getWeiBalance(address _user, uint _index) public view returns(Types.Wei memory) { Types.Wei[] memory weiBalances; (,,weiBalances) = soloMargin.getAccountBalances(getAccount(_user, _index)); return weiBalances[daiMarketId]; } function getParBalance(address _user, uint _index) public view returns(Types.Par memory) { Types.Par[] memory parBalances; (,parBalances,) = soloMargin.getAccountBalances(getAccount(_user, _index)); return parBalances[daiMarketId]; } function getAccount(address _user, uint _index) public pure returns(Account.Info memory) { Account.Info memory account = Account.Info({ owner: _user, number: _index }); return account; } } abstract contract ISoloMargin { struct OperatorArg { address operator; bool trusted; } function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) public virtual; function getAccountBalances( Account.Info memory account ) public view virtual returns ( address[] memory, Types.Par[] memory, Types.Wei[] memory ); function setOperators( OperatorArg[] memory args ) public virtual; function getNumMarkets() public view virtual returns (uint256); function getMarketTokenAddress(uint256 marketId) public view virtual returns (address); } library Account { // ============ Enums ============ /* * Most-recently-cached account status. * * Normal: Can only be liquidated if the account values are violating the global margin-ratio. * Liquid: Can be liquidated no matter the account values. * Can be vaporized if there are no more positive account values. * Vapor: Has only negative (or zeroed) account values. Can be vaporized. * */ enum Status { Normal, Liquid, Vapor } // ============ Structs ============ // Represents the unique key that specifies an account struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } // The complete storage for any account struct Storage { mapping (uint256 => Types.Par) balances; // Mapping from marketId to principal Status status; } // ============ Library Functions ============ function equals( Info memory a, Info memory b ) internal pure returns (bool) { return a.owner == b.owner && a.number == b.number; } } library Actions { // ============ Constants ============ bytes32 constant FILE = "Actions"; // ============ Enums ============ enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AccountLayout { OnePrimary, TwoPrimary, PrimaryAndSecondary } enum MarketLayout { ZeroMarkets, OneMarket, TwoMarkets } // ============ Structs ============ /* * Arguments that are passed to Solo in an ordered list as part of a single operation. * Each ActionArgs has an actionType which specifies which action struct that this data will be * parsed into before being processed. */ struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } // ============ Action Types ============ /* * Moves tokens from an address to Solo. Can either repay a borrow or provide additional supply. */ struct DepositArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address from; } /* * Moves tokens from Solo to another address. Can either borrow tokens or reduce the amount * previously supplied. */ struct WithdrawArgs { Types.AssetAmount amount; Account.Info account; uint256 market; address to; } /* * Transfers balance between two accounts. The msg.sender must be an operator for both accounts. * The amount field applies to accountOne. * This action does not require any token movement since the trade is done internally to Solo. */ struct TransferArgs { Types.AssetAmount amount; Account.Info accountOne; Account.Info accountTwo; uint256 market; } /* * Acquires a certain amount of tokens by spending other tokens. Sends takerMarket tokens to the * specified exchangeWrapper contract and expects makerMarket tokens in return. The amount field * applies to the makerMarket. */ struct BuyArgs { Types.AssetAmount amount; Account.Info account; uint256 makerMarket; uint256 takerMarket; address exchangeWrapper; bytes orderData; } /* * Spends a certain amount of tokens to acquire other tokens. Sends takerMarket tokens to the * specified exchangeWrapper and expects makerMarket tokens in return. The amount field applies * to the takerMarket. */ struct SellArgs { Types.AssetAmount amount; Account.Info account; uint256 takerMarket; uint256 makerMarket; address exchangeWrapper; bytes orderData; } /* * Trades balances between two accounts using any external contract that implements the * AutoTrader interface. The AutoTrader contract must be an operator for the makerAccount (for * which it is trading on-behalf-of). The amount field applies to the makerAccount and the * inputMarket. This proposed change to the makerAccount is passed to the AutoTrader which will * quote a change for the makerAccount in the outputMarket (or will disallow the trade). * This action does not require any token movement since the trade is done internally to Solo. */ struct TradeArgs { Types.AssetAmount amount; Account.Info takerAccount; Account.Info makerAccount; uint256 inputMarket; uint256 outputMarket; address autoTrader; bytes tradeData; } /* * Each account must maintain a certain margin-ratio (specified globally). If the account falls * below this margin-ratio, it can be liquidated by any other account. This allows anyone else * (arbitrageurs) to repay any borrowed asset (owedMarket) of the liquidating account in * exchange for any collateral asset (heldMarket) of the liquidAccount. The ratio is determined * by the price ratio (given by the oracles) plus a spread (specified globally). Liquidating an * account also sets a flag on the account that the account is being liquidated. This allows * anyone to continue liquidating the account until there are no more borrows being taken by the * liquidating account. Liquidators do not have to liquidate the entire account all at once but * can liquidate as much as they choose. The liquidating flag allows liquidators to continue * liquidating the account even if it becomes collateralized through partial liquidation or * price movement. */ struct LiquidateArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info liquidAccount; uint256 owedMarket; uint256 heldMarket; } /* * Similar to liquidate, but vaporAccounts are accounts that have only negative balances * remaining. The arbitrageur pays back the negative asset (owedMarket) of the vaporAccount in * exchange for a collateral asset (heldMarket) at a favorable spread. However, since the * liquidAccount has no collateral assets, the collateral must come from Solo's excess tokens. */ struct VaporizeArgs { Types.AssetAmount amount; Account.Info solidAccount; Account.Info vaporAccount; uint256 owedMarket; uint256 heldMarket; } /* * Passes arbitrary bytes of data to an external contract that implements the Callee interface. * Does not change any asset amounts. This function may be useful for setting certain variables * on layer-two contracts for certain accounts without having to make a separate Ethereum * transaction for doing so. Also, the second-layer contracts can ensure that the call is coming * from an operator of the particular account. */ struct CallArgs { Account.Info account; address callee; bytes data; } // ============ Helper Functions ============ function getMarketLayout( ActionType actionType ) internal pure returns (MarketLayout) { if ( actionType == Actions.ActionType.Deposit || actionType == Actions.ActionType.Withdraw || actionType == Actions.ActionType.Transfer ) { return MarketLayout.OneMarket; } else if (actionType == Actions.ActionType.Call) { return MarketLayout.ZeroMarkets; } return MarketLayout.TwoMarkets; } function getAccountLayout( ActionType actionType ) internal pure returns (AccountLayout) { if ( actionType == Actions.ActionType.Transfer || actionType == Actions.ActionType.Trade ) { return AccountLayout.TwoPrimary; } else if ( actionType == Actions.ActionType.Liquidate || actionType == Actions.ActionType.Vaporize ) { return AccountLayout.PrimaryAndSecondary; } return AccountLayout.OnePrimary; } // ============ Parsing Functions ============ function parseDepositArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (DepositArgs memory) { assert(args.actionType == ActionType.Deposit); return DepositArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, from: args.otherAddress }); } function parseWithdrawArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (WithdrawArgs memory) { assert(args.actionType == ActionType.Withdraw); return WithdrawArgs({ amount: args.amount, account: accounts[args.accountId], market: args.primaryMarketId, to: args.otherAddress }); } function parseTransferArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TransferArgs memory) { assert(args.actionType == ActionType.Transfer); return TransferArgs({ amount: args.amount, accountOne: accounts[args.accountId], accountTwo: accounts[args.otherAccountId], market: args.primaryMarketId }); } function parseBuyArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (BuyArgs memory) { assert(args.actionType == ActionType.Buy); return BuyArgs({ amount: args.amount, account: accounts[args.accountId], makerMarket: args.primaryMarketId, takerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseSellArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (SellArgs memory) { assert(args.actionType == ActionType.Sell); return SellArgs({ amount: args.amount, account: accounts[args.accountId], takerMarket: args.primaryMarketId, makerMarket: args.secondaryMarketId, exchangeWrapper: args.otherAddress, orderData: args.data }); } function parseTradeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (TradeArgs memory) { assert(args.actionType == ActionType.Trade); return TradeArgs({ amount: args.amount, takerAccount: accounts[args.accountId], makerAccount: accounts[args.otherAccountId], inputMarket: args.primaryMarketId, outputMarket: args.secondaryMarketId, autoTrader: args.otherAddress, tradeData: args.data }); } function parseLiquidateArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (LiquidateArgs memory) { assert(args.actionType == ActionType.Liquidate); return LiquidateArgs({ amount: args.amount, solidAccount: accounts[args.accountId], liquidAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseVaporizeArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (VaporizeArgs memory) { assert(args.actionType == ActionType.Vaporize); return VaporizeArgs({ amount: args.amount, solidAccount: accounts[args.accountId], vaporAccount: accounts[args.otherAccountId], owedMarket: args.primaryMarketId, heldMarket: args.secondaryMarketId }); } function parseCallArgs( Account.Info[] memory accounts, ActionArgs memory args ) internal pure returns (CallArgs memory) { assert(args.actionType == ActionType.Call); return CallArgs({ account: accounts[args.accountId], callee: args.otherAddress, data: args.data }); } } library Math { using SafeMath for uint256; // ============ Constants ============ bytes32 constant FILE = "Math"; // ============ Library Functions ============ /* * Return target * (numerator / denominator). */ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { return target.mul(numerator).div(denominator); } /* * Return target * (numerator / denominator), but rounded up. */ function getPartialRoundUp( uint256 target, uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (target == 0 || numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return target.mul(numerator).sub(1).div(denominator).add(1); } function to128( uint256 number ) internal pure returns (uint128) { uint128 result = uint128(number); Require.that( result == number, FILE, "Unsafe cast to uint128" ); return result; } function to96( uint256 number ) internal pure returns (uint96) { uint96 result = uint96(number); Require.that( result == number, FILE, "Unsafe cast to uint96" ); return result; } function to32( uint256 number ) internal pure returns (uint32) { uint32 result = uint32(number); Require.that( result == number, FILE, "Unsafe cast to uint32" ); return result; } function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } library Types { using Math for uint256; // ============ AssetAmount ============ enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } // ============ Par (Principal Amount) ============ // Total borrow and supply values for a market struct TotalPar { uint128 borrow; uint128 supply; } // Individual principal amount for an account struct Par { bool sign; // true if positive uint128 value; } function zeroPar() internal pure returns (Par memory) { return Par({ sign: false, value: 0 }); } function sub( Par memory a, Par memory b ) internal pure returns (Par memory) { return add(a, negative(b)); } function add( Par memory a, Par memory b ) internal pure returns (Par memory) { Par memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value).to128(); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value).to128(); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value).to128(); } } return result; } function equals( Par memory a, Par memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Par memory a ) internal pure returns (Par memory) { return Par({ sign: !a.sign, value: a.value }); } function isNegative( Par memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Par memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Par memory a ) internal pure returns (bool) { return a.value == 0; } // ============ Wei (Token Amount) ============ // Individual token amount for an account struct Wei { bool sign; // true if positive uint256 value; } function zeroWei() internal pure returns (Wei memory) { return Wei({ sign: false, value: 0 }); } function sub( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { return add(a, negative(b)); } function add( Wei memory a, Wei memory b ) internal pure returns (Wei memory) { Wei memory result; if (a.sign == b.sign) { result.sign = a.sign; result.value = SafeMath.add(a.value, b.value); } else { if (a.value >= b.value) { result.sign = a.sign; result.value = SafeMath.sub(a.value, b.value); } else { result.sign = b.sign; result.value = SafeMath.sub(b.value, a.value); } } return result; } function equals( Wei memory a, Wei memory b ) internal pure returns (bool) { if (a.value == b.value) { if (a.value == 0) { return true; } return a.sign == b.sign; } return false; } function negative( Wei memory a ) internal pure returns (Wei memory) { return Wei({ sign: !a.sign, value: a.value }); } function isNegative( Wei memory a ) internal pure returns (bool) { return !a.sign && a.value > 0; } function isPositive( Wei memory a ) internal pure returns (bool) { return a.sign && a.value > 0; } function isZero( Wei memory a ) internal pure returns (bool) { return a.value == 0; } } contract FulcrumSavingsProtocol is ProtocolInterface, DSAuth { address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public savingsProxy; uint public decimals = 10 ** 18; function addSavingsProxy(address _savingsProxy) public auth { savingsProxy = _savingsProxy; } function deposit(address _user, uint _amount) public override { require(msg.sender == _user); // get dai from user require(ERC20(DAI_ADDRESS).transferFrom(_user, address(this), _amount)); // approve dai to Fulcrum ERC20(DAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); // mint iDai ITokenInterface(NEW_IDAI_ADDRESS).mint(_user, _amount); } function withdraw(address _user, uint _amount) public override { require(msg.sender == _user); // transfer all users tokens to our contract require(ERC20(NEW_IDAI_ADDRESS).transferFrom(_user, address(this), ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(_user))); // approve iDai to that contract ERC20(NEW_IDAI_ADDRESS).approve(NEW_IDAI_ADDRESS, uint(-1)); uint tokenPrice = ITokenInterface(NEW_IDAI_ADDRESS).tokenPrice(); // get dai from iDai contract ITokenInterface(NEW_IDAI_ADDRESS).burn(_user, _amount * decimals / tokenPrice); // return all remaining tokens back to user require(ERC20(NEW_IDAI_ADDRESS).transfer(_user, ITokenInterface(NEW_IDAI_ADDRESS).balanceOf(address(this)))); } } contract LoanShifterTaker is AdminAuth, ProxyPermission { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; Manager public constant manager = Manager(MANAGER_ADDRESS); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2612Af3A521c2df9EAF28422Ca335b04AdF3ac66); enum Protocols { MCD, COMPOUND } enum SwapType { NO_SWAP, COLL_SWAP, DEBT_SWAP } struct LoanShiftData { Protocols fromProtocol; Protocols toProtocol; SwapType swapType; bool wholeDebt; uint collAmount; uint debtAmount; address debtAddr1; address debtAddr2; address addrLoan1; address addrLoan2; uint id1; uint id2; } /// @notice Main entry point, it will move or transform a loan /// @dev Called through DSProxy function moveLoan( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) public { if (_isSameTypeVaults(_loanShift)) { _forkVault(_loanShift); return; } _callCloseAndOpen(_exchangeData, _loanShift); } //////////////////////// INTERNAL FUNCTIONS ////////////////////////// function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); uint loanAmount = _loanShift.debtAmount; if (_loanShift.wholeDebt) { loanAmount = ILoanShifter(protoAddr).getLoanAmount(_loanShift.id1, _loanShift.addrLoan1); } ( uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData ) = _packData(_loanShift, _exchangeData); // encode data bytes memory paramsData = abi.encode(numData, addrData, enumData, callData, address(this)); address payable loanShifterReceiverAddr = payable(shifterRegistry.getAddr("LOAN_SHIFTER_RECEIVER")); // call FL givePermission(loanShifterReceiverAddr); lendingPool.flashLoan(loanShifterReceiverAddr, getLoanAddr(_loanShift.debtAddr1, _loanShift.fromProtocol), loanAmount, paramsData); removePermission(loanShifterReceiverAddr); } function _forkVault(LoanShiftData memory _loanShift) internal { // Create new Vault to move to if (_loanShift.id2 == 0) { _loanShift.id2 = manager.open(manager.ilks(_loanShift.id1), address(this)); } if (_loanShift.wholeDebt) { manager.shift(_loanShift.id1, _loanShift.id2); } } function _isSameTypeVaults(LoanShiftData memory _loanShift) internal pure returns (bool) { return _loanShift.fromProtocol == Protocols.MCD && _loanShift.toProtocol == Protocols.MCD && _loanShift.addrLoan1 == _loanShift.addrLoan2; } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } function getLoanAddr(address _address, Protocols _fromProtocol) internal returns (address) { if (_fromProtocol == Protocols.COMPOUND) { return CTokenInterface(_address).underlying(); } else if (_fromProtocol == Protocols.MCD) { return DAI_ADDRESS; } else { return address(0); } } function _packData( LoanShiftData memory _loanShift, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[8] memory addrData, uint8[3] memory enumData, bytes memory callData) { numData = [ _loanShift.collAmount, _loanShift.debtAmount, _loanShift.id1, _loanShift.id2, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ _loanShift.addrLoan1, _loanShift.addrLoan2, _loanShift.debtAddr1, _loanShift.debtAddr2, exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper ]; enumData = [ uint8(_loanShift.fromProtocol), uint8(_loanShift.toProtocol), uint8(_loanShift.swapType) ]; callData = exchangeData.callData; } } contract ShifterRegistry is AdminAuth { mapping (string => address) public contractAddresses; bool public finalized; function changeContractAddr(string memory _contractName, address _protoAddr) public onlyOwner { require(!finalized); contractAddresses[_contractName] = _protoAddr; } function lock() public onlyOwner { finalized = true; } function getAddr(string memory _contractName) public view returns (address contractAddr) { contractAddr = contractAddresses[_contractName]; require(contractAddr != address(0), "No contract address registred"); } } 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"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract DFSProxy is Auth { string public constant NAME = "DFSProxy"; string public constant VERSION = "v0.1"; mapping(address => mapping(uint => bool)) public nonces; // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("callProxy(address _user,address _proxy,address _contract,bytes _txData,uint256 _nonce)"); constructor(uint256 chainId_) public { DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(NAME)), keccak256(bytes(VERSION)), chainId_, address(this) )); } function callProxy(address _user, address _proxy, address _contract, bytes calldata _txData, uint256 _nonce, uint8 _v, bytes32 _r, bytes32 _s) external payable onlyAuthorized { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _user, _proxy, _contract, _txData, _nonce)) )); // user must be proxy owner require(DSProxyInterface(_proxy).owner() == _user); require(_user == ecrecover(digest, _v, _r, _s), "DFSProxy/user-not-valid"); require(!nonces[_user][_nonce], "DFSProxy/invalid-nonce"); nonces[_user][_nonce] = true; DSProxyInterface(_proxy).execute{value: msg.value}(_contract, _txData); } } contract DebugInfo { mapping (string => uint) public uintValues; mapping (string => address) public addrValues; mapping (string => string) public stringValues; mapping (string => bytes32) public bytes32Values; function logUint(string memory _id, uint _value) public { uintValues[_id] = _value; } function logAddr(string memory _id, address _value) public { addrValues[_id] = _value; } function logString(string memory _id, string memory _value) public { stringValues[_id] = _value; } function logBytes32(string memory _id, bytes32 _value) public { bytes32Values[_id] = _value; } } contract Discount { address public owner; mapping(address => CustomServiceFee) public serviceFees; uint256 constant MAX_SERVICE_FEE = 400; struct CustomServiceFee { bool active; uint256 amount; } constructor() public { owner = msg.sender; } function isCustomFeeSet(address _user) public view returns (bool) { return serviceFees[_user].active; } function getCustomServiceFee(address _user) public view returns (uint256) { return serviceFees[_user].amount; } function setServiceFee(address _user, uint256 _fee) public { require(msg.sender == owner, "Only owner"); require(_fee >= MAX_SERVICE_FEE || _fee == 0); serviceFees[_user] = CustomServiceFee({active: true, amount: _fee}); } function disableServiceFee(address _user) public { require(msg.sender == owner, "Only owner"); serviceFees[_user] = CustomServiceFee({active: false, amount: 0}); } } contract DydxFlashLoanBase { using SafeMath for uint256; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; function _getMarketIdFromTokenAddress(address token) internal view returns (uint256) { return 0; } function _getRepaymentAmountInternal(uint256 amount) internal view returns (uint256) { // Needs to be overcollateralize // Needs to provide +2 wei to be safe return amount.add(2); } function _getAccountInfo() internal view returns (Account.Info memory) { return Account.Info({owner: address(this), number: 1}); } function _getWithdrawAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } function _getCallAction(bytes memory data, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: data }); } function _getDepositAction(uint marketId, uint256 amount, address contractAddr) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: contractAddr, otherAccountId: 0, data: "" }); } } contract ExchangeDataParser { function decodeExchangeData( SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (address[4] memory, uint[4] memory, bytes memory) { return ( [exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper], [exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x], exchangeData.callData ); } function encodeExchangeData( address[4] memory exAddr, uint[4] memory exNum, bytes memory callData ) internal pure returns (SaverExchangeCore.ExchangeData memory) { return SaverExchangeCore.ExchangeData({ srcAddr: exAddr[0], destAddr: exAddr[1], srcAmount: exNum[0], destAmount: exNum[1], minPrice: exNum[2], wrapper: exAddr[3], exchangeAddr: exAddr[2], callData: callData, price0x: exNum[3] }); } } interface IFlashLoanReceiver { function executeOperation(address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external; } abstract contract ILendingPoolAddressesProvider { function getLendingPool() public view virtual returns (address); function setLendingPoolImpl(address _pool) public virtual; function getLendingPoolCore() public virtual view returns (address payable); function setLendingPoolCoreImpl(address _lendingPoolCore) public virtual; function getLendingPoolConfigurator() public virtual view returns (address); function setLendingPoolConfiguratorImpl(address _configurator) public virtual; function getLendingPoolDataProvider() public virtual view returns (address); function setLendingPoolDataProviderImpl(address _provider) public virtual; function getLendingPoolParametersProvider() public virtual view returns (address); function setLendingPoolParametersProviderImpl(address _parametersProvider) public virtual; function getTokenDistributor() public virtual view returns (address); function setTokenDistributor(address _tokenDistributor) public virtual; function getFeeProvider() public virtual view returns (address); function setFeeProviderImpl(address _feeProvider) public virtual; function getLendingPoolLiquidationManager() public virtual view returns (address); function setLendingPoolLiquidationManager(address _manager) public virtual; function getLendingPoolManager() public virtual view returns (address); function setLendingPoolManager(address _lendingPoolManager) public virtual; function getPriceOracle() public virtual view returns (address); function setPriceOracle(address _priceOracle) public virtual; function getLendingRateOracle() public view virtual returns (address); function setLendingRateOracle(address _lendingRateOracle) public virtual; } library EthAddressLib { function ethAddress() internal pure returns(address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } } abstract contract FlashLoanReceiverBase is IFlashLoanReceiver { using SafeERC20 for ERC20; using SafeMath for uint256; ILendingPoolAddressesProvider public addressesProvider; constructor(ILendingPoolAddressesProvider _provider) public { addressesProvider = _provider; } receive () external virtual payable {} function transferFundsBackToPoolInternal(address _reserve, uint256 _amount) internal { address payable core = addressesProvider.getLendingPoolCore(); transferInternal(core,_reserve, _amount); } function transferInternal(address payable _destination, address _reserve, uint256 _amount) internal { if(_reserve == EthAddressLib.ethAddress()) { //solium-disable-next-line _destination.call{value: _amount}(""); return; } ERC20(_reserve).safeTransfer(_destination, _amount); } function getBalanceInternal(address _target, address _reserve) internal view returns(uint256) { if(_reserve == EthAddressLib.ethAddress()) { return _target.balance; } return ERC20(_reserve).balanceOf(_target); } } contract GasBurner { // solhint-disable-next-line const-name-snakecase GasTokenInterface public constant gasToken = GasTokenInterface(0x0000000000b3F879cb30FE243b4Dfee438691c04); modifier burnGas(uint _amount) { if (gasToken.balanceOf(address(this)) >= _amount) { gasToken.free(_amount); } _; } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 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. */ function safeApprove(ERC20 token, address spender, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 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(ERC20 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)); } function _callOptionalReturn(ERC20 token, bytes memory data) private { 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"); } } } 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) { // 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) { 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; } } contract ZrxAllowlist is AdminAuth { mapping (address => bool) public zrxAllowlist; function setAllowlistAddr(address _zrxAddr, bool _state) public onlyOwner { zrxAllowlist[_zrxAddr] = _state; } function isZrxAddr(address _zrxAddr) public view returns (bool) { return zrxAllowlist[_zrxAddr]; } } contract AaveBasicProxy is GasBurner { using SafeERC20 for ERC20; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant AAVE_LENDING_POOL_ADDRESSES = 0x24a42fD28C976A61Df5D00D0599C34c4f90748c8; uint16 public constant AAVE_REFERRAL_CODE = 64; /// @notice User deposits tokens to the Aave protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _amount Amount of tokens to be deposited function deposit(address _tokenAddr, uint256 _amount) public burnGas(5) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint ethValue = _amount; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); approveToken(_tokenAddr, lendingPoolCore); ethValue = 0; } ILendingPool(lendingPool).deposit{value: ethValue}(_tokenAddr, _amount, AAVE_REFERRAL_CODE); setUserUseReserveAsCollateralIfNeeded(_tokenAddr); } /// @notice User withdraws tokens from the Aave protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _aTokenAddr ATokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _wholeAmount If true we will take the whole amount on chain function withdraw(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeAmount) public burnGas(8) { uint256 amount = _wholeAmount ? ERC20(_aTokenAddr).balanceOf(address(this)) : _amount; IAToken(_aTokenAddr).redeem(amount); withdrawTokens(_tokenAddr); } /// @notice User borrows tokens to the Aave protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _type Send 1 for variable rate and 2 for fixed rate function borrow(address _tokenAddr, uint256 _amount, uint256 _type) public burnGas(8) { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).borrow(_tokenAddr, _amount, _type, AAVE_REFERRAL_CODE); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (_wholeDebt) { amount = borrowAmount; } amount += originationFee; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, payable(address(this))); withdrawTokens(_tokenAddr); } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Aave protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _aTokenAddr ATokens to be paybacked /// @param _amount Amount of tokens to be payed back /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function paybackOnBehalf(address _tokenAddr, address _aTokenAddr, uint256 _amount, bool _wholeDebt, address payable _onBehalf) public burnGas(3) payable { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); uint256 amount = _amount; (,uint256 borrowAmount,,,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, _onBehalf); if (_wholeDebt) { amount = borrowAmount; } amount += originationFee; if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), amount); approveToken(_tokenAddr, lendingPoolCore); } ILendingPool(lendingPool).repay{value: msg.value}(_tokenAddr, amount, _onBehalf); withdrawTokens(_tokenAddr); } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { uint256 amount = _tokenAddr == ETH_ADDR ? address(this).balance : ERC20(_tokenAddr).balanceOf(address(this)); if (amount > 0) { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, amount); } else { msg.sender.transfer(amount); } } } /// @notice Approves token contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _caller Address which will gain the approval function approveToken(address _tokenAddr, address _caller) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_caller, 0); ERC20(_tokenAddr).safeApprove(_caller, uint256(-1)); } } function setUserUseReserveAsCollateralIfNeeded(address _tokenAddr) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_tokenAddr, address(this)); if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, true); } } function setUserUseReserveAsCollateral(address _tokenAddr, bool _true) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).setUserUseReserveAsCollateral(_tokenAddr, _true); } function swapBorrowRateMode(address _reserve) public { address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); ILendingPool(lendingPool).swapBorrowRateMode(_reserve); } } contract AaveLoanInfo is AaveSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint256[] collAmounts; uint256[] borrowAmounts; } struct TokenInfo { address aTokenAddress; address underlyingTokenAddress; uint256 collateralFactor; uint256 price; } struct TokenInfoFull { address aTokenAddress; address underlyingTokenAddress; uint256 supplyRate; uint256 borrowRate; uint256 totalSupply; uint256 availableLiquidity; uint256 totalBorrow; uint256 collateralFactor; uint256 price; bool usageAsCollateralEnabled; } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint256) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Aave prices for tokens /// @param _tokens Arr. of tokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _tokens) public view returns (uint256[] memory prices) { address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); prices = new uint[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { prices[i] = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokens[i]); } } /// @notice Fetches Aave collateral factors for tokens /// @param _tokens Arr. of tokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _tokens) public view returns (uint256[] memory collFactors) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); collFactors = new uint256[](_tokens.length); for (uint256 i = 0; i < _tokens.length; ++i) { (,collFactors[i],,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokens[i]); } } function getTokenBalances(address _user, address[] memory _tokens) public view returns (uint256[] memory balances, uint256[] memory borrows, bool[] memory enabledAsCollateral) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); balances = new uint256[](_tokens.length); borrows = new uint256[](_tokens.length); enabledAsCollateral = new bool[](_tokens.length); for (uint256 i = 0; i < _tokens.length; i++) { address asset = _tokens[i]; (balances[i], borrows[i],,,,,,,,enabledAsCollateral[i]) = ILendingPool(lendingPoolAddress).getUserReserveData(asset, _user); } } /// @notice Calcualted the ratio of coll/debt for an aave user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint256[] memory ratios) { ratios = new uint256[](_users.length); for (uint256 i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about reserves /// @param _tokenAddresses Array of tokens addresses /// @return tokens Array of reserves infomartion function getTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfo[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfo[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfo({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]) }); } } /// @notice Information about reserves /// @param _tokenAddresses Array of token addresses /// @return tokens Array of reserves infomartion function getFullTokensInfo(address[] memory _tokenAddresses) public view returns(TokenInfoFull[] memory tokens) { address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); tokens = new TokenInfoFull[](_tokenAddresses.length); for (uint256 i = 0; i < _tokenAddresses.length; ++i) { (,uint256 ltv,,bool usageAsCollateralEnabled) = ILendingPool(lendingPoolCoreAddress).getReserveConfiguration(_tokenAddresses[i]); tokens[i] = TokenInfoFull({ aTokenAddress: ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(_tokenAddresses[i]), underlyingTokenAddress: _tokenAddresses[i], supplyRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentLiquidityRate(_tokenAddresses[i]), borrowRate: ILendingPool(lendingPoolCoreAddress).getReserveCurrentVariableBorrowRate(_tokenAddresses[i]), totalSupply: ILendingPool(lendingPoolCoreAddress).getReserveTotalLiquidity(_tokenAddresses[i]), availableLiquidity: ILendingPool(lendingPoolCoreAddress).getReserveAvailableLiquidity(_tokenAddresses[i]), totalBorrow: ILendingPool(lendingPoolCoreAddress).getReserveTotalBorrowsVariable(_tokenAddresses[i]), collateralFactor: ltv, price: IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(_tokenAddresses[i]), usageAsCollateralEnabled: usageAsCollateralEnabled }); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address lendingPoolAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address priceOracleAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getPriceOracle(); address[] memory reserves = ILendingPool(lendingPoolAddress).getReserves(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](reserves.length), borrowAddr: new address[](reserves.length), collAmounts: new uint[](reserves.length), borrowAmounts: new uint[](reserves.length) }); uint64 collPos = 0; uint64 borrowPos = 0; for (uint64 i = 0; i < reserves.length; i++) { address reserve = reserves[i]; (uint256 aTokenBalance, uint256 borrowBalance,,,,,,,,) = ILendingPool(lendingPoolAddress).getUserReserveData(reserve, _user); uint256 price = IPriceOracleGetterAave(priceOracleAddress).getAssetPrice(reserves[i]); if (aTokenBalance > 0) { uint256 userTokenBalanceEth = wmul(aTokenBalance, price); data.collAddr[collPos] = reserve; data.collAmounts[collPos] = userTokenBalanceEth; collPos++; } // Sum up debt in Eth if (borrowBalance > 0) { uint256 userBorrowBalanceEth = wmul(borrowBalance, price); data.borrowAddr[borrowPos] = reserve; data.borrowAmounts[borrowPos] = userBorrowBalanceEth; borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } /// @notice Fetches all the collateral/debt address and amounts, denominated in ether /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } } contract AaveMonitor is AdminAuth, DSMath, AaveSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 19; uint public BOOST_GAS_TOKEN = 19; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2000000; uint public BOOST_GAS_COST = 2000000; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; AaveMonitorProxy public aaveMonitorProxy; AaveSubscriptions public subscriptionsContract; address public aaveSaverProxy; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _aaveMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Aave positions /// @param _aaveSaverProxy Contract that actually performs Repay/Boost constructor(address _aaveMonitorProxy, address _subscriptions, address _aaveSaverProxy) public { approvedCallers[msg.sender] = true; aaveMonitorProxy = AaveMonitorProxy(_aaveMonitorProxy); subscriptionsContract = AaveSubscriptions(_subscriptions); aaveSaverProxy = _aaveSaverProxy; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "repay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _user The actual address that owns the Aave position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); aaveMonitorProxy.callExecute{value: msg.value}( _user, aaveSaverProxy, abi.encodeWithSignature( "boost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),uint256)", _exData, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticAaveBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by AaveMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); AaveSubscriptions.AaveHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Aave position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { AaveSubscriptions.AaveHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change gas token amount /// @param _gasTokenAmount New gas token amount /// @param _repay true if repay gas token, false if boost gas token function changeGasTokenAmount(uint _gasTokenAmount, bool _repay) public onlyOwner { if (_repay) { REPAY_GAS_TOKEN = _gasTokenAmount; } else { BOOST_GAS_TOKEN = _gasTokenAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract AaveMonitorProxy is AdminAuth { using SafeERC20 for ERC20; uint public CHANGE_PERIOD; address public monitor; address public newMonitor; address public lastMonitor; uint public changeRequestedTimestamp; mapping(address => bool) public allowed; event MonitorChangeInitiated(address oldMonitor, address newMonitor); event MonitorChangeCanceled(); event MonitorChangeFinished(address monitor); event MonitorChangeReverted(address monitor); // if someone who is allowed become malicious, owner can't be changed modifier onlyAllowed() { require(allowed[msg.sender] || msg.sender == owner); _; } modifier onlyMonitor() { require (msg.sender == monitor); _; } constructor(uint _changePeriod) public { CHANGE_PERIOD = _changePeriod * 1 days; } /// @notice Only monitor contract is able to call execute on users proxy /// @param _owner Address of cdp owner (users DSProxy address) /// @param _aaveSaverProxy Address of AaveSaverProxy /// @param _data Data to send to AaveSaverProxy function callExecute(address _owner, address _aaveSaverProxy, bytes memory _data) public payable onlyMonitor { // execute reverts if calling specific method fails DSProxyInterface(_owner).execute{value: msg.value}(_aaveSaverProxy, _data); // return if anything left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /// @notice Allowed users are able to set Monitor contract without any waiting period first time /// @param _monitor Address of Monitor contract function setMonitor(address _monitor) public onlyAllowed { require(monitor == address(0)); monitor = _monitor; } /// @notice Allowed users are able to start procedure for changing monitor /// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change /// @param _newMonitor address of new monitor function changeMonitor(address _newMonitor) public onlyAllowed { require(changeRequestedTimestamp == 0); changeRequestedTimestamp = now; lastMonitor = monitor; newMonitor = _newMonitor; emit MonitorChangeInitiated(lastMonitor, newMonitor); } /// @notice At any point allowed users are able to cancel monitor change function cancelMonitorChange() public onlyAllowed { require(changeRequestedTimestamp > 0); changeRequestedTimestamp = 0; newMonitor = address(0); emit MonitorChangeCanceled(); } /// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started function confirmNewMonitor() public onlyAllowed { require((changeRequestedTimestamp + CHANGE_PERIOD) < now); require(changeRequestedTimestamp != 0); require(newMonitor != address(0)); monitor = newMonitor; newMonitor = address(0); changeRequestedTimestamp = 0; emit MonitorChangeFinished(monitor); } /// @notice Its possible to revert monitor to last used monitor function revertMonitor() public onlyAllowed { require(lastMonitor != address(0)); monitor = lastMonitor; emit MonitorChangeReverted(monitor); } /// @notice Allowed users are able to add new allowed user /// @param _user Address of user that will be allowed function addAllowed(address _user) public onlyAllowed { allowed[_user] = true; } /// @notice Allowed users are able to remove allowed user /// @dev owner is always allowed even if someone tries to remove it from allowed mapping /// @param _user Address of allowed user function removeAllowed(address _user) public onlyAllowed { allowed[_user] = false; } function setChangePeriod(uint _periodInDays) public onlyAllowed { require(_periodInDays * 1 days > CHANGE_PERIOD); CHANGE_PERIOD = _periodInDays * 1 days; } /// @notice In case something is left in contract, owner is able to withdraw it /// @param _token address of token to withdraw balance function withdrawToken(address _token) public onlyOwner { uint balance = ERC20(_token).balanceOf(address(this)); ERC20(_token).safeTransfer(msg.sender, balance); } /// @notice In case something is left in contract, owner is able to withdraw it function withdrawEth() public onlyOwner { uint balance = address(this).balance; msg.sender.transfer(balance); } } contract AaveSubscriptions is AdminAuth { struct AaveHolder { address user; uint128 minRatio; uint128 maxRatio; uint128 optimalRatioBoost; uint128 optimalRatioRepay; bool boostEnabled; } struct SubPosition { uint arrPos; bool subscribed; } AaveHolder[] public subscribers; mapping (address => SubPosition) public subscribersPos; uint public changeIndex; event Subscribed(address indexed user); event Unsubscribed(address indexed user); event Updated(address indexed user); event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool); /// @dev Called by the DSProxy contract which owns the Aave position /// @notice Adds the users Aave poistion in the list of subscriptions so it can be monitored /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalBoost Ratio amount which boost should target /// @param _optimalRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external { // if boost is not enabled, set max ratio to max uint uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1); require(checkParams(_minRatio, localMaxRatio), "Must be correct params"); SubPosition storage subInfo = subscribersPos[msg.sender]; AaveHolder memory subscription = AaveHolder({ minRatio: _minRatio, maxRatio: localMaxRatio, optimalRatioBoost: _optimalBoost, optimalRatioRepay: _optimalRepay, user: msg.sender, boostEnabled: _boostEnabled }); changeIndex++; if (subInfo.subscribed) { subscribers[subInfo.arrPos] = subscription; emit Updated(msg.sender); emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled); } else { subscribers.push(subscription); subInfo.arrPos = subscribers.length - 1; subInfo.subscribed = true; emit Subscribed(msg.sender); } } /// @notice Called by the users DSProxy /// @dev Owner who subscribed cancels his subscription function unsubscribe() external { _unsubscribe(msg.sender); } /// @dev Checks limit if minRatio is bigger than max /// @param _minRatio Minimum ratio, bellow which repay can be triggered /// @param _maxRatio Maximum ratio, over which boost can be triggered /// @return Returns bool if the params are correct function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) { if (_minRatio > _maxRatio) { return false; } return true; } /// @dev Internal method to remove a subscriber from the list /// @param _user The actual address that owns the Aave position function _unsubscribe(address _user) internal { require(subscribers.length > 0, "Must have subscribers in the list"); SubPosition storage subInfo = subscribersPos[_user]; require(subInfo.subscribed, "Must first be subscribed"); address lastOwner = subscribers[subscribers.length - 1].user; SubPosition storage subInfo2 = subscribersPos[lastOwner]; subInfo2.arrPos = subInfo.arrPos; subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1]; subscribers.pop(); // remove last element and reduce arr length changeIndex++; subInfo.subscribed = false; subInfo.arrPos = 0; emit Unsubscribed(msg.sender); } /// @dev Checks if the user is subscribed /// @param _user The actual address that owns the Aave position /// @return If the user is subscribed function isSubscribed(address _user) public view returns (bool) { SubPosition storage subInfo = subscribersPos[_user]; return subInfo.subscribed; } /// @dev Returns subscribtion information about a user /// @param _user The actual address that owns the Aave position /// @return Subscription information about the user if exists function getHolder(address _user) public view returns (AaveHolder memory) { SubPosition storage subInfo = subscribersPos[_user]; return subscribers[subInfo.arrPos]; } /// @notice Helper method to return all the subscribed CDPs /// @return List of all subscribers function getSubscribers() public view returns (AaveHolder[] memory) { return subscribers; } /// @notice Helper method for the frontend, returns all the subscribed CDPs paginated /// @param _page What page of subscribers you want /// @param _perPage Number of entries per page /// @return List of all subscribers for that page function getSubscribersByPage(uint _page, uint _perPage) public view returns (AaveHolder[] memory) { AaveHolder[] memory holders = new AaveHolder[](_perPage); uint start = _page * _perPage; uint end = start + _perPage; end = (end > holders.length) ? holders.length : end; uint count = 0; for (uint i = start; i < end; i++) { holders[count] = subscribers[i]; count++; } return holders; } ////////////// ADMIN METHODS /////////////////// /// @notice Admin function to unsubscribe a position /// @param _user The actual address that owns the Aave position function unsubscribeByAdmin(address _user) public onlyOwner { SubPosition storage subInfo = subscribersPos[_user]; if (subInfo.subscribed) { _unsubscribe(_user); } } } contract AaveSubscriptionsProxy is ProxyPermission { address public constant AAVE_SUBSCRIPTION_ADDRESS = 0xe08ff7A2BADb634F0b581E675E6B3e583De086FC; address public constant AAVE_MONITOR_PROXY = 0xfA560Dba3a8D0B197cA9505A2B98120DD89209AC; /// @notice Calls subscription contract and creates a DSGuard if non existent /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function subscribe( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { givePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe( _minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls subscription contract and updated existing parameters /// @dev If subscription is non existent this will create one /// @param _minRatio Minimum ratio below which repay is triggered /// @param _maxRatio Maximum ratio after which boost is triggered /// @param _optimalRatioBoost Ratio amount which boost should target /// @param _optimalRatioRepay Ratio amount which repay should target /// @param _boostEnabled Boolean determing if boost is enabled function update( uint128 _minRatio, uint128 _maxRatio, uint128 _optimalRatioBoost, uint128 _optimalRatioRepay, bool _boostEnabled ) public { IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).subscribe(_minRatio, _maxRatio, _optimalRatioBoost, _optimalRatioRepay, _boostEnabled); } /// @notice Calls the subscription contract to unsubscribe the caller function unsubscribe() public { removePermission(AAVE_MONITOR_PROXY); IAaveSubscription(AAVE_SUBSCRIPTION_ADDRESS).unsubscribe(); } } contract AaveImport is AaveHelper, AdminAuth { using SafeERC20 for ERC20; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant BASIC_PROXY = 0x9D266997bc73B27d4302E711b55FD78B5278e1De; address public constant AETH_ADDRESS = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04; function callFunction( address sender, Account.Info memory account, bytes memory data ) public { ( address collateralToken, address borrowToken, uint256 ethAmount, address user, address proxy ) = abi.decode(data, (address,address,uint256,address,address)); // withdraw eth TokenInterface(WETH_ADDRESS).withdraw(ethAmount); address lendingPoolCoreAddress = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address aCollateralToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(collateralToken); address aBorrowToken = ILendingPool(lendingPoolCoreAddress).getReserveATokenAddress(borrowToken); // deposit eth on behalf of proxy DSProxy(payable(proxy)).execute{value: ethAmount}(BASIC_PROXY, abi.encodeWithSignature("deposit(address,uint256)", ETH_ADDR, ethAmount)); // borrow needed amount to repay users borrow (,uint256 borrowAmount,,uint256 borrowRateMode,,,uint256 originationFee,,,) = ILendingPool(lendingPool).getUserReserveData(borrowToken, user); borrowAmount += originationFee; DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("borrow(address,uint256,uint256)", borrowToken, borrowAmount, borrowRateMode)); // payback on behalf of user ERC20(borrowToken).safeApprove(proxy, borrowAmount); DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("paybackOnBehalf(address,address,uint256,bool,address)", borrowToken, aBorrowToken, 0, true, user)); // pull tokens from user to proxy ERC20(aCollateralToken).safeTransferFrom(user, proxy, ERC20(aCollateralToken).balanceOf(user)); // enable as collateral DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("setUserUseReserveAsCollateralIfNeeded(address)", collateralToken)); // withdraw deposited eth DSProxy(payable(proxy)).execute(BASIC_PROXY, abi.encodeWithSignature("withdraw(address,address,uint256,bool)", ETH_ADDR, AETH_ADDRESS, ethAmount, false)); // deposit eth, get weth and return to sender TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); ERC20(WETH_ADDRESS).safeTransfer(proxy, ethAmount+2); } /// @dev if contract receive eth, convert it to WETH receive() external payable { // deposit eth and get weth if (msg.sender == owner) { TokenInterface(WETH_ADDRESS).deposit.value(address(this).balance)(); } } } contract AaveImportTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address payable public constant AAVE_IMPORT = 0x44e4EF23b4794699D0625657cADcB96e07820fFe; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must send 2 wei with this transaction /// @dev User must approve AaveImport to pull _aCollateralToken /// @param _collateralToken Collateral token we are moving to DSProxy /// @param _borrowToken Borrow token we are moving to DSProxy /// @param _ethAmount ETH amount that needs to be pulled from dydx function importLoan(address _collateralToken, address _borrowToken, uint _ethAmount) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, AAVE_IMPORT); operations[1] = _getCallAction( abi.encode(_collateralToken, _borrowToken, _ethAmount, msg.sender, address(this)), AAVE_IMPORT ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(AAVE_IMPORT); solo.operate(accountInfos, operations); removePermission(AAVE_IMPORT); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveImport", abi.encode(_collateralToken, _borrowToken)); } } contract CompoundBasicProxy is GasBurner { address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; using SafeERC20 for ERC20; /// @notice User deposits tokens to the Compound protocol /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @param _tokenAddr The address of the token to be deposited /// @param _cTokenAddr CTokens to be deposited /// @param _amount Amount of tokens to be deposited /// @param _inMarket True if the token is already in market for that address function deposit(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(5) payable { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); } approveToken(_tokenAddr, _cTokenAddr); if (!_inMarket) { enterMarket(_cTokenAddr); } if (_tokenAddr != ETH_ADDR) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0); } else { CEtherInterface(_cTokenAddr).mint{value: msg.value}(); // reverts on fail } } /// @notice User withdraws tokens to the Compound protocol /// @param _tokenAddr The address of the token to be withdrawn /// @param _cTokenAddr CTokens to be withdrawn /// @param _amount Amount of tokens to be withdrawn /// @param _isCAmount If true _amount is cTokens if falls _amount is underlying tokens function withdraw(address _tokenAddr, address _cTokenAddr, uint _amount, bool _isCAmount) public burnGas(5) { if (_isCAmount) { require(CTokenInterface(_cTokenAddr).redeem(_amount) == 0); } else { require(CTokenInterface(_cTokenAddr).redeemUnderlying(_amount) == 0); } // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice User borrows tokens to the Compound protocol /// @param _tokenAddr The address of the token to be borrowed /// @param _cTokenAddr CTokens to be borrowed /// @param _amount Amount of tokens to be borrowed /// @param _inMarket True if the token is already in market for that address function borrow(address _tokenAddr, address _cTokenAddr, uint _amount, bool _inMarket) public burnGas(8) { if (!_inMarket) { enterMarket(_cTokenAddr); } require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); // withdraw funds to msg.sender if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @dev User needs to approve the DSProxy to pull the _tokenAddr tokens /// @notice User paybacks tokens to the Compound protocol /// @param _tokenAddr The address of the token to be paybacked /// @param _cTokenAddr CTokens to be paybacked /// @param _amount Amount of tokens to be payedback /// @param _wholeDebt If true the _amount will be set to the whole amount of the debt function payback(address _tokenAddr, address _cTokenAddr, uint _amount, bool _wholeDebt) public burnGas(5) payable { approveToken(_tokenAddr, _cTokenAddr); if (_wholeDebt) { _amount = CTokenInterface(_cTokenAddr).borrowBalanceCurrent(address(this)); } if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransferFrom(msg.sender, address(this), _amount); require(CTokenInterface(_cTokenAddr).repayBorrow(_amount) == 0); } else { CEtherInterface(_cTokenAddr).repayBorrow{value: msg.value}(); msg.sender.transfer(address(this).balance); // send back the extra eth } } /// @notice Helper method to withdraw tokens from the DSProxy /// @param _tokenAddr Address of the token to be withdrawn function withdrawTokens(address _tokenAddr) public { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeTransfer(msg.sender, ERC20(_tokenAddr).balanceOf(address(this))); } else { msg.sender.transfer(address(this).balance); } } /// @notice Enters the Compound market so it can be deposited/borrowed /// @param _cTokenAddr CToken address of the token function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } /// @notice Exits the Compound market so it can't be deposited/borrowed /// @param _cTokenAddr CToken address of the token function exitMarket(address _cTokenAddr) public { ComptrollerInterface(COMPTROLLER_ADDR).exitMarket(_cTokenAddr); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDR) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, 0); ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } } contract CompoundSafetyRatio is Exponential, DSMath { // solhint-disable-next-line const-name-snakecase ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); /// @notice Calcualted the ratio of debt / adjusted collateral /// @param _user Address of the user function getSafetyRatio(address _user) public view returns (uint) { // For each asset the account is in address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); uint sumCollateral = 0; uint sumBorrow = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { (, uint collFactorMantissa) = comp.markets(address(asset)); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice); (, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral); } // Sum up debt in Usd if (borrowBalance != 0) { (, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow); } } if (sumBorrow == 0) return uint(-1); uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral; return wdiv(1e18, borrowPowerUsed); } } contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio, GasBurner { using SafeERC20 for ERC20; enum Method { Boost, Repay } uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 20; uint constant public MAX_GAS_PRICE = 80000000000; // 80 gwei uint public REPAY_GAS_COST = 2200000; uint public BOOST_GAS_COST = 1700000; address public constant GAS_TOKEN_INTERFACE_ADDRESS = 0x0000000000b3F879cb30FE243b4Dfee438691c04; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; CompoundMonitorProxy public compoundMonitorProxy; CompoundSubscriptions public subscriptionsContract; address public compoundFlashLoanTakerAddress; DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } /// @param _compoundMonitorProxy Proxy contracts that actually is authorized to call DSProxy /// @param _subscriptions Subscriptions contract for Compound positions /// @param _compoundFlashLoanTaker Contract that actually performs Repay/Boost constructor(address _compoundMonitorProxy, address _subscriptions, address _compoundFlashLoanTaker) public { approvedCallers[msg.sender] = true; compoundMonitorProxy = CompoundMonitorProxy(_compoundMonitorProxy); subscriptionsContract = CompoundSubscriptions(_subscriptions); compoundFlashLoanTakerAddress = _compoundFlashLoanTaker; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function repayFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(REPAY_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "repayWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _user The actual address that owns the Compound position function boostFor( SaverExchangeCore.ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress address _user ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _user); require(isAllowed); // check if conditions are met uint256 gasCost = calcGasCost(BOOST_GAS_COST); compoundMonitorProxy.callExecute{value: msg.value}( _user, compoundFlashLoanTakerAddress, abi.encodeWithSignature( "boostWithLoan((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256)", _exData, _cAddresses, gasCost ) ); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _user); require(isGoodRatio); // check if the after result of the actions is good returnEth(); logger.Log(address(this), _user, "AutomaticCompoundBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if it can be called and the ratio function canCall(Method _method, address _user) public view returns(bool, uint) { bool subscribed = subscriptionsContract.isSubscribed(_user); CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call /// @param _method Type of action to be called /// @param _user The actual address that owns the Compound position /// @return Boolean if the recent action preformed correctly and the ratio function ratioGoodAfter(Method _method, address _user) public view returns(bool, uint) { CompoundSubscriptions.CompoundHolder memory holder; holder= subscriptionsContract.getHolder(_user); uint currRatio = getSafetyRatio(_user); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } /// @notice If any tokens gets stuck in the contract owner can withdraw it /// @param _tokenAddress Address of the ERC20 token /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferERC20(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).safeTransfer(_to, _amount); } /// @notice If any Eth gets stuck in the contract owner can withdraw it /// @param _to Address of the receiver /// @param _amount The amount to be sent function transferEth(address payable _to, uint _amount) public onlyOwner { _to.transfer(_amount); } } contract CompoundSaverHelper is DSMath, Exponential { using SafeERC20 for ERC20; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; address public constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant COMPOUND_LOGGER = 0x3DD0CDf5fFA28C6847B4B276e2fD256046a44bb7; /// @notice Helper method to payback the Compound debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _user Owner of the compound position we are paying back function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer((_amount - wholeDebt)); } else { ERC20(_borrowToken).safeTransfer(_user, (_amount - wholeDebt)); } _amount = wholeDebt; } approveCToken(_borrowToken, _cBorrowToken); if (_borrowToken == ETH_ADDRESS) { CEtherInterface(_cBorrowToken).repayBorrow{value: _amount}(); } else { require(CTokenInterface(_cBorrowToken).repayBorrow(_amount) == 0); } } /// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(_user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(_user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); _gasCost = wdiv(_gasCost, tokenPriceInEth); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint usdTokenPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cTokenAddr); uint ethPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(CETH_ADDRESS); uint tokenPriceInEth = wdiv(usdTokenPrice, ethPrice); feeAmount = wdiv(_gasCost, tokenPriceInEth); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } /// @notice Enters the market for the collatera and borrow tokens /// @param _cTokenAddrColl Collateral address we are entering the market in /// @param _cTokenAddrBorrow Borrow address we are entering the market in function enterMarket(address _cTokenAddrColl, address _cTokenAddrBorrow) internal { address[] memory markets = new address[](2); markets[0] = _cTokenAddrColl; markets[1] = _cTokenAddrBorrow; ComptrollerInterface(COMPTROLLER).enterMarkets(markets); } /// @notice Approves CToken contract to pull underlying tokens from the DSProxy /// @param _tokenAddr Token we are trying to approve /// @param _cTokenAddr Address which will gain the approval function approveCToken(address _tokenAddr, address _cTokenAddr) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeApprove(_cTokenAddr, uint(-1)); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } /// @notice Returns the owner of the DSProxy that called the contract function getUserAddress() internal view returns (address) { DSProxy proxy = DSProxy(uint160(address(this))); return proxy.owner(); } /// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); if (liquidityInUsd == 0) return usersBalance; CTokenInterface(_cCollAddress).accrueInterest(); (, uint collFactorMantissa) = ComptrollerInterface(COMPTROLLER).markets(_cCollAddress); Exp memory collateralFactor = Exp({mantissa: collFactorMantissa}); (, uint tokensToUsd) = divScalarByExpTruncate(liquidityInUsd, collateralFactor); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cCollAddress); uint liqInToken = wdiv(tokensToUsd, usdPrice); if (liqInToken > usersBalance) return usersBalance; return sub(liqInToken, (liqInToken / 100)); // cut off 1% due to rounding issues } /// @notice Returns the maximum amount of borrow amount available /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cBorrowAddress Borrow token we are getting the max value of /// @param _account Users account /// @return Returns the max. borrow amount in that token function getMaxBorrow(address _cBorrowAddress, address _account) public returns (uint) { (, uint liquidityInUsd, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); address oracle = ComptrollerInterface(COMPTROLLER).oracle(); CTokenInterface(_cBorrowAddress).accrueInterest(); uint usdPrice = CompoundOracleInterface(oracle).getUnderlyingPrice(_cBorrowAddress); uint liquidityInToken = wdiv(liquidityInUsd, usdPrice); return sub(liquidityInToken, (liquidityInToken / 100)); // cut off 1% due to rounding issues } } contract CompoundImportFlashLoan is FlashLoanReceiverBase { using SafeERC20 for ERC20; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant COMPOUND_BORROW_PROXY = 0xb7EDC39bE76107e2Cc645f0f6a3D164f5e173Ee2; address public owner; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( address cCollateralToken, address cBorrowToken, address user, address proxy ) = abi.decode(_params, (address,address,address,address)); // approve FL tokens so we can repay them ERC20(_reserve).safeApprove(cBorrowToken, uint(-1)); // repay compound debt require(CTokenInterface(cBorrowToken).repayBorrowBehalf(user, uint(-1)) == 0, "Repay borrow behalf fail"); // transfer cTokens to proxy uint cTokenBalance = CTokenInterface(cCollateralToken).balanceOf(user); require(CTokenInterface(cCollateralToken).transferFrom(user, proxy, cTokenBalance)); // borrow bytes memory proxyData = getProxyData(cCollateralToken, cBorrowToken, _reserve, (_amount + _fee)); DSProxyInterface(proxy).execute(COMPOUND_BORROW_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); } /// @notice Formats function data call so we can call it through DSProxy /// @param _cCollToken CToken address of collateral /// @param _cBorrowToken CToken address we will borrow /// @param _borrowToken Token address we will borrow /// @param _amount Amount that will be borrowed /// @return proxyData Formated function call data function getProxyData(address _cCollToken, address _cBorrowToken, address _borrowToken, uint _amount) internal pure returns (bytes memory proxyData) { proxyData = abi.encodeWithSignature( "borrow(address,address,address,uint256)", _cCollToken, _cBorrowToken, _borrowToken, _amount); } function withdrawStuckFunds(address _tokenAddr, uint _amount) public { require(owner == msg.sender, "Must be owner"); if (_tokenAddr == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { msg.sender.transfer(_amount); } else { ERC20(_tokenAddr).safeTransfer(owner, _amount); } } } contract CompoundImportTaker is CompoundSaverHelper, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_IMPORT_FLASH_LOAN = 0x0a9238e14d5A20CDb03811B12D1984587C3CE9a0; address public constant PROXY_REGISTRY_ADDRESS = 0x4678f0a6958e4D2Bc4F1BAF7Bc52E8F3564f3fE4; DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); givePermission(COMPOUND_IMPORT_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_IMPORT_FLASH_LOAN, getUnderlyingAddr(_cBorrowToken), loanAmount, paramsData); removePermission(COMPOUND_IMPORT_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundImport", abi.encode(loanAmount, 0, _cCollateralToken)); } /// @notice Gets proxy address, if user doesn't has DSProxy build it /// @return proxy DsProxy address function getProxy() internal returns (address proxy) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).proxies(msg.sender); if (proxy == address(0)) { proxy = ProxyRegistryInterface(PROXY_REGISTRY_ADDRESS).build(msg.sender); } } } contract SaverExchangeCore is SaverExchangeHelper, DSMath { // first is empty to keep the legacy order in place enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX } enum ActionType { SELL, BUY } struct ExchangeData { address srcAddr; address destAddr; uint srcAmount; uint destAmount; uint minPrice; address wrapper; address exchangeAddr; bytes callData; uint256 price0x; } /// @notice Internal method that preforms a sell on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and destAmount function _sell(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; uint tokensLeft = exData.srcAmount; // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } // Try 0x first and then fallback on specific wrapper if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = exData.srcAddr == WETH_ADDRESS ? msg.value - exData.srcAmount : msg.value; (success, swapedTokens, tokensLeft) = takeOrder(exData, ethAmount, ActionType.SELL); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.SELL); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= wmul(exData.minPrice, exData.srcAmount), "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, swapedTokens); } /// @notice Internal method that preforms a buy on 0x/on-chain /// @dev Usefull for other DFS contract to integrate for exchanging /// @param exData Exchange data struct /// @return (address, uint) Address of the wrapper used and srcAmount function _buy(ExchangeData memory exData) internal returns (address, uint) { address wrapper; uint swapedTokens; bool success; require(exData.destAmount != 0, "Dest amount must be specified"); // if selling eth, convert to weth if (exData.srcAddr == KYBER_ETH_ADDRESS) { exData.srcAddr = ethToWethAddr(exData.srcAddr); TokenInterface(WETH_ADDRESS).deposit.value(exData.srcAmount)(); } if (exData.price0x > 0) { approve0xProxy(exData.srcAddr, exData.srcAmount); uint ethAmount = exData.srcAddr == WETH_ADDRESS ? msg.value - exData.srcAmount : msg.value; (success, swapedTokens,) = takeOrder(exData, ethAmount, ActionType.BUY); if (success) { wrapper = exData.exchangeAddr; } } // fallback to desired wrapper if 0x failed if (!success) { swapedTokens = saverSwap(exData, ActionType.BUY); wrapper = exData.wrapper; } require(getBalance(exData.destAddr) >= exData.destAmount, "Final amount isn't correct"); // if anything is left in weth, pull it to user as eth if (getBalance(WETH_ADDRESS) > 0) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } return (wrapper, getBalance(exData.destAddr)); } /// @notice Takes order from 0x and returns bool indicating if it is successful /// @param _exData Exchange data /// @param _ethAmount Ether fee needed for 0x order function takeOrder( ExchangeData memory _exData, uint256 _ethAmount, ActionType _type ) private returns (bool success, uint256, uint256) { // write in the exact amount we are selling/buing in an order if (_type == ActionType.SELL) { writeUint256(_exData.callData, 36, _exData.srcAmount); } else { writeUint256(_exData.callData, 36, _exData.destAmount); } if (ZrxAllowlist(ZRX_ALLOWLIST_ADDR).isZrxAddr(_exData.exchangeAddr)) { (success, ) = _exData.exchangeAddr.call{value: _ethAmount}(_exData.callData); } else { success = false; } uint256 tokensSwaped = 0; uint256 tokensLeft = _exData.srcAmount; if (success) { // check to see if any _src tokens are left over after exchange tokensLeft = getBalance(_exData.srcAddr); // convert weth -> eth if needed if (_exData.destAddr == KYBER_ETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw( TokenInterface(WETH_ADDRESS).balanceOf(address(this)) ); } // get the current balance of the swaped tokens tokensSwaped = getBalance(_exData.destAddr); } return (success, tokensSwaped, tokensLeft); } /// @notice Calls wraper contract for exchage to preform an on-chain swap /// @param _exData Exchange data struct /// @param _type Type of action SELL|BUY /// @return swapedTokens For Sell that the destAmount, for Buy thats the srcAmount function saverSwap(ExchangeData memory _exData, ActionType _type) internal returns (uint swapedTokens) { require(SaverExchangeRegistry(SAVER_EXCHANGE_REGISTRY).isWrapper(_exData.wrapper), "Wrapper is not valid"); uint ethValue = 0; ERC20(_exData.srcAddr).safeTransfer(_exData.wrapper, _exData.srcAmount); if (_type == ActionType.SELL) { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). sell{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.srcAmount); } else { swapedTokens = ExchangeInterfaceV2(_exData.wrapper). buy{value: ethValue}(_exData.srcAddr, _exData.destAddr, _exData.destAmount); } } function writeUint256(bytes memory _b, uint256 _index, uint _input) internal pure { if (_b.length < _index + 32) { revert("Incorrent lengt while writting bytes32"); } bytes32 input = bytes32(_input); _index += 32; // Read the bytes32 from array memory assembly { mstore(add(_b, _index), input) } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) { // splitting in two different bytes and encoding all because of stack too deep in decoding part bytes memory part1 = abi.encode( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ); bytes memory part2 = abi.encode( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ); return abi.encode(part1, part2); } function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) { ( bytes memory part1, bytes memory part2 ) = abi.decode(_data, (bytes,bytes)); ( _exData.srcAddr, _exData.destAddr, _exData.srcAmount, _exData.destAmount ) = abi.decode(part1, (address,address,uint256,uint256)); ( _exData.minPrice, _exData.wrapper, _exData.exchangeAddr, _exData.callData, _exData.price0x ) = abi.decode(part2, (uint256,address,address,bytes,uint256)); } // solhint-disable-next-line no-empty-blocks receive() external virtual payable {} } contract KyberWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant KYBER_INTERFACE = 0x9AAb3f75489902f3a48495025729a0AF77d4b11e; address payable public constant WALLET_ID = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), _srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, _srcAmount, destToken, msg.sender, uint(-1), 0, WALLET_ID ); return destAmount; } /// @notice Buys a _destAmount of tokens at Kyber /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { ERC20 srcToken = ERC20(_srcAddr); ERC20 destToken = ERC20(_destAddr); uint srcAmount = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmount = srcToken.balanceOf(address(this)); } else { srcAmount = msg.value; } KyberNetworkProxyInterface kyberNetworkProxy = KyberNetworkProxyInterface(KYBER_INTERFACE); if (_srcAddr != KYBER_ETH_ADDRESS) { srcToken.safeApprove(address(kyberNetworkProxy), srcAmount); } uint destAmount = kyberNetworkProxy.trade{value: msg.value}( srcToken, srcAmount, destToken, msg.sender, _destAmount, 0, WALLET_ID ); require(destAmount == _destAmount, "Wrong dest amount"); uint srcAmountAfter = 0; if (_srcAddr != KYBER_ETH_ADDRESS) { srcAmountAfter = srcToken.balanceOf(address(this)); } else { srcAmountAfter = address(this).balance; } // Send the leftover from the source token back sendLeftOver(_srcAddr); return (srcAmount - srcAmountAfter); } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return rate Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint rate) { (rate, ) = KyberNetworkProxyInterface(KYBER_INTERFACE) .getExpectedRate(ERC20(_srcAddr), ERC20(_destAddr), _srcAmount); // multiply with decimal difference in src token rate = rate * (10**(18 - getDecimals(_srcAddr))); // divide with decimal difference in dest token rate = rate / (10**(18 - getDecimals(_destAddr))); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return rate Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint rate) { uint256 srcRate = getSellRate(_srcAddr, _destAddr, _destAmount); uint256 srcAmount = wmul(_destAmount, srcRate); rate = getSellRate(_destAddr, _srcAddr, srcAmount); // increase rate by 3% too account for inaccuracy between sell/buy conversion rate = rate + (rate / 30); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } receive() payable external {} function getDecimals(address _token) internal view returns (uint256) { if (_token == KYBER_ETH_ADDRESS) return 18; return ERC20(_token).decimals(); } } contract OasisTradeWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { using SafeERC20 for ERC20; address public constant OTC_ADDRESS = 0x794e6e91555438aFc3ccF1c5076A74F42133d08D; address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Sells a _srcAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external override payable returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, _srcAmount); uint destAmount = OasisInterface(OTC_ADDRESS).sellAllAmount(srcAddr, _srcAmount, destAddr, 0); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(destAmount); msg.sender.transfer(destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, destAmount); } return destAmount; } /// @notice Buys a _destAmount of tokens at Oasis /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); ERC20(srcAddr).safeApprove(OTC_ADDRESS, uint(-1)); uint srcAmount = OasisInterface(OTC_ADDRESS).buyAllAmount(destAddr, _destAmount, srcAddr, uint(-1)); // convert weth -> eth and send back if (destAddr == WETH_ADDRESS) { TokenInterface(WETH_ADDRESS).withdraw(_destAmount); msg.sender.transfer(_destAmount); } else { ERC20(destAddr).safeTransfer(msg.sender, _destAmount); } // Send the leftover from the source token back sendLeftOver(srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getBuyAmount(destAddr, srcAddr, _srcAmount), _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { address srcAddr = ethToWethAddr(_srcAddr); address destAddr = ethToWethAddr(_destAddr); return wdiv(OasisInterface(OTC_ADDRESS).getPayAmount(srcAddr, destAddr, _destAmount), _destAmount); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapV2Wrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; UniswapRouterInterface public constant router = UniswapRouterInterface(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), _srcAmount); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapExactTokensForETH(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } // if we are selling token to token else { amounts = router.swapExactTokensForTokens(_srcAmount, 1, path, msg.sender, block.timestamp + 1); } return amounts[amounts.length - 1]; } /// @notice Buys a _destAmount of tokens at UniswapV2 /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); uint[] memory amounts; address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; ERC20(_srcAddr).safeApprove(address(router), uint(-1)); // if we are buying ether if (_destAddr == WETH_ADDRESS) { amounts = router.swapTokensForExactETH(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // if we are buying token to token else { amounts = router.swapTokensForExactTokens(_destAmount, uint(-1), path, msg.sender, block.timestamp + 1); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return amounts[0]; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsOut(_srcAmount, path); return wdiv(amounts[amounts.length - 1], _srcAmount); } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); address[] memory path = new address[](2); path[0] = _srcAddr; path[1] = _destAddr; uint[] memory amounts = router.getAmountsIn(_destAmount, path); return wdiv(amounts[0], _destAmount); } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract UniswapWrapper is DSMath, ExchangeInterfaceV2, AdminAuth { address public constant WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant KYBER_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant UNISWAP_FACTORY = 0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95; using SafeERC20 for ERC20; /// @notice Sells a _srcAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Destination amount function sell(address _srcAddr, address _destAddr, uint _srcAmount) external payable override returns (uint) { address uniswapExchangeAddr; uint destAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferInput(_srcAmount, 1, block.timestamp + 1, msg.sender); } // if we are selling token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, _srcAmount); destAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferInput(_srcAmount, 1, 1, block.timestamp + 1, msg.sender, _destAddr); } return destAmount; } /// @notice Buys a _destAmount of tokens at Uniswap /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint srcAmount function buy(address _srcAddr, address _destAddr, uint _destAmount) external override payable returns(uint) { address uniswapExchangeAddr; uint srcAmount; _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); // if we are buying ether if (_destAddr == WETH_ADDRESS) { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToEthTransferOutput(_destAmount, uint(-1), block.timestamp + 1, msg.sender); } // if we are buying token to token else { uniswapExchangeAddr = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); ERC20(_srcAddr).safeApprove(uniswapExchangeAddr, uint(-1)); srcAmount = UniswapExchangeInterface(uniswapExchangeAddr). tokenToTokenTransferOutput(_destAmount, uint(-1), uint(-1), block.timestamp + 1, msg.sender, _destAddr); } // Send the leftover from the source token back sendLeftOver(_srcAddr); return srcAmount; } /// @notice Return a rate for which we can sell an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _srcAmount From amount /// @return uint Rate function getSellRate(address _srcAddr, address _destAddr, uint _srcAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenInputPrice(_srcAmount), _srcAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthInputPrice(_srcAmount), _srcAmount); } else { uint ethBought = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getTokenToEthInputPrice(_srcAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getEthToTokenInputPrice(ethBought), _srcAmount); } } /// @notice Return a rate for which we can buy an amount of tokens /// @param _srcAddr From token /// @param _destAddr To token /// @param _destAmount To amount /// @return uint Rate function getBuyRate(address _srcAddr, address _destAddr, uint _destAmount) public override view returns (uint) { _srcAddr = ethToWethAddr(_srcAddr); _destAddr = ethToWethAddr(_destAddr); if(_srcAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getEthToTokenOutputPrice(_destAmount), _destAmount); } else if (_destAddr == WETH_ADDRESS) { address uniswapTokenAddress = UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr); return wdiv(UniswapExchangeInterface(uniswapTokenAddress).getTokenToEthOutputPrice(_destAmount), _destAmount); } else { uint ethNeeded = UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_destAddr)).getTokenToEthOutputPrice(_destAmount); return wdiv(UniswapExchangeInterface(UniswapFactoryInterface(UNISWAP_FACTORY).getExchange(_srcAddr)).getEthToTokenOutputPrice(ethNeeded), _destAmount); } } /// @notice Send any leftover tokens, we use to clear out srcTokens after buy /// @param _srcAddr Source token address function sendLeftOver(address _srcAddr) internal { msg.sender.transfer(address(this).balance); if (_srcAddr != KYBER_ETH_ADDRESS) { ERC20(_srcAddr).safeTransfer(msg.sender, ERC20(_srcAddr).balanceOf(address(this))); } } /// @notice Converts Kybers Eth address -> Weth /// @param _src Input address function ethToWethAddr(address _src) internal pure returns (address) { return _src == KYBER_ETH_ADDRESS ? WETH_ADDRESS : _src; } receive() payable external {} } contract DyDxFlashLoanTaker is DydxFlashLoanBase, ProxyPermission { address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; /// @notice Takes flash loan for _receiver /// @dev Receiver must send back WETH + 2 wei after executing transaction /// @dev Method is meant to be called from proxy and proxy will give authorization to _receiver /// @param _receiver Address of funds receiver /// @param _ethAmount ETH amount that needs to be pulled from dydx /// @param _encodedData Bytes with packed data function takeLoan(address _receiver, uint256 _ethAmount, bytes memory _encodedData) public { ISoloMargin solo = ISoloMargin(SOLO_MARGIN_ADDRESS); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(WETH_ADDR); // Calculate repay amount (_amount + (2 wei)) // Approve transfer from uint256 repayAmount = _getRepaymentAmountInternal(_ethAmount); ERC20(WETH_ADDR).approve(SOLO_MARGIN_ADDRESS, repayAmount); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, _ethAmount, _receiver); operations[1] = _getCallAction( _encodedData, _receiver ); operations[2] = _getDepositAction(marketId, repayAmount, address(this)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(); givePermission(_receiver); solo.operate(accountInfos, operations); removePermission(_receiver); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "DyDxFlashLoanTaken", abi.encode(_receiver, _ethAmount, _encodedData)); } } abstract contract CTokenInterface is ERC20 { function mint(uint256 mintAmount) external virtual returns (uint256); // function mint() external virtual payable; function accrueInterest() public virtual returns (uint); function redeem(uint256 redeemTokens) external virtual returns (uint256); function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256); function borrow(uint256 borrowAmount) external virtual returns (uint256); function repayBorrow(uint256 repayAmount) external virtual returns (uint256); function repayBorrow() external virtual payable; function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256); function repayBorrowBehalf(address borrower) external virtual payable; function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral) external virtual returns (uint256); function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable; function exchangeRateCurrent() external virtual returns (uint256); function supplyRatePerBlock() external virtual returns (uint256); function borrowRatePerBlock() external virtual returns (uint256); function totalReserves() external virtual returns (uint256); function reserveFactorMantissa() external virtual returns (uint256); function borrowBalanceCurrent(address account) external virtual returns (uint256); function totalBorrowsCurrent() external virtual returns (uint256); function getCash() external virtual returns (uint256); function balanceOfUnderlying(address owner) external virtual returns (uint256); function underlying() external virtual returns (address); function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint); } abstract contract ISubscriptionsV2 is StaticV2 { function getOwner(uint _cdpId) external view virtual returns(address); function getSubscribedInfo(uint _cdpId) public view virtual returns(bool, uint128, uint128, uint128, uint128, address, uint coll, uint debt); function getCdpHolder(uint _cdpId) public view virtual returns (bool subscribed, CdpHolder memory); } contract MCDMonitorV2 is DSMath, AdminAuth, GasBurner, StaticV2 { uint public REPAY_GAS_TOKEN = 25; uint public BOOST_GAS_TOKEN = 25; uint public MAX_GAS_PRICE = 200000000000; // 200 gwei uint public REPAY_GAS_COST = 2500000; uint public BOOST_GAS_COST = 2500000; MCDMonitorProxyV2 public monitorProxyContract; ISubscriptionsV2 public subscriptionsContract; address public mcdSaverTakerAddress; Manager public manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); Vat public vat = Vat(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B); Spotter public spotter = Spotter(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @dev Addresses that are able to call methods for repay and boost mapping(address => bool) public approvedCallers; modifier onlyApproved() { require(approvedCallers[msg.sender]); _; } constructor(address _monitorProxy, address _subscriptions, address _mcdSaverTakerAddress) public { approvedCallers[msg.sender] = true; monitorProxyContract = MCDMonitorProxyV2(_monitorProxy); subscriptionsContract = ISubscriptionsV2(_subscriptions); mcdSaverTakerAddress = _mcdSaverTakerAddress; } /// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function repayFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(REPAY_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "repayWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Repay, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDRepay", abi.encode(ratioBefore, ratioAfter)); } /// @notice Bots call this method to boost for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction function boostFor( uint _cdpId, uint _nextPrice, address _joinAddr, SaverExchangeCore.ExchangeData memory _exchangeData ) public payable onlyApproved burnGas(BOOST_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Boost, _cdpId, _nextPrice); require(isAllowed); uint gasCost = calcGasCost(BOOST_GAS_COST); address owner = subscriptionsContract.getOwner(_cdpId); monitorProxyContract.callExecute{value: msg.value}( owner, mcdSaverTakerAddress, abi.encodeWithSignature( "boostWithLoan(uint256,uint256,address,(address,address,uint256,uint256,uint256,address,address,bytes,uint256))", _cdpId, gasCost, _joinAddr, _exchangeData)); (bool isGoodRatio, uint ratioAfter) = ratioGoodAfter(Method.Boost, _cdpId, _nextPrice); require(isGoodRatio); returnEth(); logger.Log(address(this), owner, "AutomaticMCDBoost", abi.encode(ratioBefore, ratioAfter)); } /******************* INTERNAL METHODS ********************************/ function returnEth() internal { // return if some eth left if (address(this).balance > 0) { msg.sender.transfer(address(this).balance); } } /******************* STATIC METHODS ********************************/ /// @notice Returns an address that owns the CDP /// @param _cdpId Id of the CDP function getOwner(uint _cdpId) public view returns(address) { return manager.owns(_cdpId); } /// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt) / (10 ** 18); } /// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); // check if using next price is allowed if (_nextPrice > 0 && !holder.nextPriceEnabled) return (false, 0); // check if boost and boost allowed if (_method == Method.Boost && !holder.boostEnabled) return (false, 0); // check if owner is still owner if (getOwner(_cdpId) != holder.owner) return (false, 0); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.minRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.maxRatio, currRatio); } } /// @dev After the Boost/Repay check if the ratio doesn't trigger another call function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (currRatio < holder.maxRatio, currRatio); } else if (_method == Method.Boost) { return (currRatio > holder.minRatio, currRatio); } } /// @notice Calculates gas cost (in Eth) of tx /// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP /// @param _gasAmount Amount of gas used for the tx function calcGasCost(uint _gasAmount) public view returns (uint) { uint gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE; return mul(gasPrice, _gasAmount); } /******************* OWNER ONLY OPERATIONS ********************************/ /// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions /// @param _gasCost New gas cost for boost method function changeBoostGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); BOOST_GAS_COST = _gasCost; } /// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions /// @param _gasCost New gas cost for repay method function changeRepayGasCost(uint _gasCost) public onlyOwner { require(_gasCost < 3000000); REPAY_GAS_COST = _gasCost; } /// @notice Allows owner to change max gas price /// @param _maxGasPrice New max gas price function changeMaxGasPrice(uint _maxGasPrice) public onlyOwner { require(_maxGasPrice < 500000000000); MAX_GAS_PRICE = _maxGasPrice; } /// @notice Allows owner to change the amount of gas token burned per function call /// @param _gasAmount Amount of gas token /// @param _isRepay Flag to know for which function we are setting the gas token amount function changeGasTokenAmount(uint _gasAmount, bool _isRepay) public onlyOwner { if (_isRepay) { REPAY_GAS_TOKEN = _gasAmount; } else { BOOST_GAS_TOKEN = _gasAmount; } } /// @notice Adds a new bot address which will be able to call repay/boost /// @param _caller Bot address function addCaller(address _caller) public onlyOwner { approvedCallers[_caller] = true; } /// @notice Removes a bot address so it can't call repay/boost /// @param _caller Bot address function removeCaller(address _caller) public onlyOwner { approvedCallers[_caller] = false; } } contract MCDCloseFlashLoan is SaverExchangeCore, MCDSaverProxyHelper, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 internal constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); struct CloseData { uint cdpId; uint collAmount; uint daiAmount; uint minAccepted; address joinAddr; address proxy; uint flFee; bool toDai; address reserve; uint amount; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { ( uint[8] memory numData, address[5] memory addrData, bytes memory callData, address proxy, bool toDai ) = abi.decode(_params, (uint256[8],address[5],bytes,address,bool)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[7] }); CloseData memory closeData = CloseData({ cdpId: numData[0], collAmount: numData[1], daiAmount: numData[2], minAccepted: numData[3], joinAddr: addrData[4], proxy: proxy, flFee: _fee, toDai: toDai, reserve: _reserve, amount: _amount }); address user = DSProxy(payable(closeData.proxy)).owner(); closeCDP(closeData, exchangeData, user); } function closeCDP( CloseData memory _closeData, ExchangeData memory _exchangeData, address _user ) internal { paybackDebt(_closeData.cdpId, manager.ilks(_closeData.cdpId), _closeData.daiAmount); // payback whole debt drawMaxCollateral(_closeData.cdpId, _closeData.joinAddr, _closeData.collAmount); // draw whole collateral uint daiSwaped = 0; uint dfsFee = 0; if (_closeData.toDai) { _exchangeData.srcAmount = _closeData.collAmount; (, daiSwaped) = _sell(_exchangeData); dfsFee = getFee(daiSwaped, _user); } else { dfsFee = getFee(_closeData.daiAmount, _user); _exchangeData.destAmount = (_closeData.daiAmount + _closeData.flFee + dfsFee); (, daiSwaped) = _buy(_exchangeData); } takeFee(dfsFee); address tokenAddr = getVaultCollAddr(_closeData.joinAddr); if (_closeData.toDai) { tokenAddr = DAI_ADDRESS; } require(getBalance(tokenAddr) >= _closeData.minAccepted, "Below min. number of eth specified"); transferFundsBackToPoolInternal(_closeData.reserve, _closeData.amount.add(_closeData.flFee)); sendLeftover(tokenAddr, DAI_ADDRESS, payable(_user)); } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal { address urn = manager.urns(_cdpId); daiJoin.dai().approve(DAI_JOIN_ADDRESS, _daiAmount); daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } function takeFee(uint _feeAmount) internal returns (uint) { ERC20(DAI_ADDRESS).transfer(WALLET_ID, _feeAmount); } function getFee(uint _amount, address _owner) internal view returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } } function getVaultCollAddr(address _joinAddr) internal view returns (address) { address tokenAddr = address(Join(_joinAddr).gem()); if (tokenAddr == WETH_ADDRESS) { return KYBER_ETH_ADDRESS; } return tokenAddr; } function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDCloseTaker is MCDSaverProxyHelper { address public constant SUBSCRIPTION_ADDRESS_NEW = 0xC45d4f6B6bf41b6EdAA58B01c4298B8d9078269a; address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); // solhint-disable-next-line const-name-snakecase Manager public constant manager = Manager(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(DEFISAVER_LOGGER); struct CloseData { uint cdpId; address joinAddr; uint collAmount; uint daiAmount; uint minAccepted; bool wholeDebt; bool toDai; } Vat public constant vat = Vat(VAT_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); function closeWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, CloseData memory _closeData, address payable mcdCloseFlashLoan ) public payable { mcdCloseFlashLoan.transfer(msg.value); // 0x fee if (_closeData.wholeDebt) { _closeData.daiAmount = getAllDebt( VAT_ADDRESS, manager.urns(_closeData.cdpId), manager.urns(_closeData.cdpId), manager.ilks(_closeData.cdpId) ); (_closeData.collAmount, ) = getCdpInfo(manager, _closeData.cdpId, manager.ilks(_closeData.cdpId)); } manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 1); (uint[8] memory numData, address[5] memory addrData, bytes memory callData) = _packData(_closeData, _exchangeData); bytes memory paramsData = abi.encode(numData, addrData, callData, address(this), _closeData.toDai); lendingPool.flashLoan(mcdCloseFlashLoan, DAI_ADDRESS, _closeData.daiAmount, paramsData); manager.cdpAllow(_closeData.cdpId, mcdCloseFlashLoan, 0); // If sub. to automatic protection unsubscribe unsubscribe(SUBSCRIPTION_ADDRESS_NEW, _closeData.cdpId); logger.Log(address(this), msg.sender, "MCDClose", abi.encode(_closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.toDai)); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint256) { (, uint256 mat) = spotter.ilks(_ilk); (, , uint256 spot, , ) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } function unsubscribe(address _subContract, uint _cdpId) internal { (, bool isSubscribed) = IMCDSubscriptions(_subContract).subscribersPos(_cdpId); if (isSubscribed) { IMCDSubscriptions(_subContract).unsubscribe(_cdpId); } } function _packData( CloseData memory _closeData, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[8] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ _closeData.cdpId, _closeData.collAmount, _closeData.daiAmount, _closeData.minAccepted, exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _closeData.joinAddr ]; callData = exchangeData.callData; } } contract MCDCreateFlashLoan is SaverExchangeCore, AdminAuth, FlashLoanReceiverBase { address public constant CREATE_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; uint public constant SERVICE_FEE = 400; // 0.25% Fee address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( uint[6] memory numData, address[5] memory addrData, bytes memory callData, address proxy ) = abi.decode(_params, (uint256[6],address[5],bytes,address)); ExchangeData memory exchangeData = ExchangeData({ srcAddr: addrData[0], destAddr: addrData[1], srcAmount: numData[2], destAmount: numData[3], minPrice: numData[4], wrapper: addrData[3], exchangeAddr: addrData[2], callData: callData, price0x: numData[5] }); openAndLeverage(numData[0], numData[1] + _fee, addrData[4], proxy, exchangeData); transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndLeverage( uint _collAmount, uint _daiAmountAndFee, address _joinAddr, address _proxy, ExchangeData memory _exchangeData ) public { uint dfsFee = getFee(_exchangeData.srcAmount, DSProxy(payable(_proxy)).owner()); _exchangeData.srcAmount = (_exchangeData.srcAmount - dfsFee); (, uint256 collSwaped) = _sell(_exchangeData); bytes32 ilk = Join(_joinAddr).ilk(); if (_joinAddr == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( MANAGER_ADDRESS, JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _daiAmountAndFee, _proxy ); } else { Join(_joinAddr).gem().approve(CREATE_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(CREATE_PROXY_ACTIONS).openLockGemAndDraw( MANAGER_ADDRESS, JUG_ADDRESS, _joinAddr, DAI_JOIN_ADDRESS, ilk, (_collAmount + collSwaped), _daiAmountAndFee, true, _proxy ); } } function getFee(uint _amount, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract MCDSaverProxy is SaverExchangeCore, MCDSaverProxyHelper { uint public constant SERVICE_FEE = 400; // 0.25% Fee bytes32 public constant ETH_ILK = 0x4554482d41000000000000000000000000000000000000000000000000000000; address public constant MANAGER_ADDRESS = 0x5ef30b9986345249bc32d8928B7ee64DE9435E39; address public constant VAT_ADDRESS = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address public constant SPOTTER_ADDRESS = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; address public constant DAI_JOIN_ADDRESS = 0x9759A6Ac90977b93B58547b4A71c78317f391A28; address public constant JUG_ADDRESS = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address public constant ETH_JOIN_ADDRESS = 0x2F0b23f53734252Bda2277357e97e1517d6B042A; address public constant DAI_ADDRESS = 0x6B175474E89094C44Da98b954EedeAC495271d0F; Manager public constant manager = Manager(MANAGER_ADDRESS); Vat public constant vat = Vat(VAT_ADDRESS); DaiJoin public constant daiJoin = DaiJoin(DAI_JOIN_ADDRESS); Spotter public constant spotter = Spotter(SPOTTER_ADDRESS); DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Repay - draws collateral, converts to Dai and repays the debt /// @dev Must be called by the DSProxy contract that owns the CDP function repay( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); drawCollateral(_cdpId, _joinAddr, _exchangeData.srcAmount); (, uint daiAmount) = _sell(_exchangeData); uint daiAfterFee = sub(daiAmount, getFee(daiAmount, _gasCost, owner)); paybackDebt(_cdpId, ilk, daiAfterFee, owner); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDRepay", abi.encode(_cdpId, owner, _exchangeData.srcAmount, daiAmount)); } /// @notice Boost - draws Dai, converts to collateral and adds to CDP /// @dev Must be called by the DSProxy contract that owns the CDP function boost( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); uint daiDrawn = drawDai(_cdpId, ilk, _exchangeData.srcAmount); uint daiAfterFee = sub(daiDrawn, getFee(daiDrawn, _gasCost, owner)); _exchangeData.srcAmount = daiAfterFee; (, uint swapedColl) = _sell(_exchangeData); addCollateral(_cdpId, _joinAddr, swapedColl); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } logger.Log(address(this), msg.sender, "MCDBoost", abi.encode(_cdpId, owner, _exchangeData.srcAmount, swapedColl)); } /// @notice Draws Dai from the CDP /// @dev If _daiAmount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to draw function drawDai(uint _cdpId, bytes32 _ilk, uint _daiAmount) internal returns (uint) { uint rate = Jug(JUG_ADDRESS).drip(_ilk); uint daiVatBalance = vat.dai(manager.urns(_cdpId)); uint maxAmount = getMaxDebt(_cdpId, _ilk); if (_daiAmount >= maxAmount) { _daiAmount = sub(maxAmount, 1); } manager.frob(_cdpId, int(0), normalizeDrawAmount(_daiAmount, rate, daiVatBalance)); manager.move(_cdpId, address(this), toRad(_daiAmount)); if (vat.can(address(this), address(DAI_JOIN_ADDRESS)) == 0) { vat.hope(DAI_JOIN_ADDRESS); } DaiJoin(DAI_JOIN_ADDRESS).exit(address(this), _daiAmount); return _daiAmount; } /// @notice Adds collateral to the CDP /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to add function addCollateral(uint _cdpId, address _joinAddr, uint _amount) internal { int convertAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().deposit{value: _amount}(); convertAmount = toPositiveInt(_amount); } else { convertAmount = toPositiveInt(convertTo18(_joinAddr, _amount)); } Join(_joinAddr).gem().approve(_joinAddr, _amount); Join(_joinAddr).join(address(this), _amount); vat.frob( manager.ilks(_cdpId), manager.urns(_cdpId), address(this), address(this), convertAmount, 0 ); } /// @notice Draws collateral and returns it to DSProxy /// @dev If _amount is bigger than max available we'll draw max /// @param _cdpId Id of the CDP /// @param _joinAddr Address of the join contract for the CDP collateral /// @param _amount Amount of collateral to draw function drawCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { uint frobAmount = _amount; if (Join(_joinAddr).dec() != 18) { frobAmount = _amount * (10 ** (18 - Join(_joinAddr).dec())); } manager.frob(_cdpId, -toPositiveInt(frobAmount), 0); manager.flux(_cdpId, address(this), frobAmount); Join(_joinAddr).exit(address(this), _amount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(_amount); // Weth -> Eth } return _amount; } /// @notice Paybacks Dai debt /// @dev If the _daiAmount is bigger than the whole debt, returns extra Dai /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _daiAmount Amount of Dai to payback /// @param _owner Address that owns the DSProxy that owns the CDP function paybackDebt(uint _cdpId, bytes32 _ilk, uint _daiAmount, address _owner) internal { address urn = manager.urns(_cdpId); uint wholeDebt = getAllDebt(VAT_ADDRESS, urn, urn, _ilk); if (_daiAmount > wholeDebt) { ERC20(DAI_ADDRESS).transfer(_owner, sub(_daiAmount, wholeDebt)); _daiAmount = wholeDebt; } if (ERC20(DAI_ADDRESS).allowance(address(this), DAI_JOIN_ADDRESS) == 0) { ERC20(DAI_ADDRESS).approve(DAI_JOIN_ADDRESS, uint(-1)); } daiJoin.join(urn, _daiAmount); manager.frob(_cdpId, 0, normalizePaybackAmount(VAT_ADDRESS, urn, _ilk)); } /// @notice Calculates the fee amount /// @param _amount Dai amount that is converted /// @param _gasCost Used for Monitor, estimated gas cost of tx /// @param _owner The address that controlls the DSProxy that owns the CDP function getFee(uint _amount, uint _gasCost, address _owner) internal returns (uint feeAmount) { uint fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(_owner)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(_owner); } feeAmount = (fee == 0) ? 0 : (_amount / fee); if (_gasCost != 0) { uint ethDaiPrice = getPrice(ETH_ILK); _gasCost = rmul(_gasCost, ethDaiPrice); feeAmount = add(feeAmount, _gasCost); } // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } ERC20(DAI_ADDRESS).transfer(WALLET_ID, feeAmount); } /// @notice Gets the maximum amount of collateral available to draw /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @param _joinAddr Joind address of collateral /// @dev Substracts 10 wei to aviod rounding error later on function getMaxCollateral(uint _cdpId, bytes32 _ilk, address _joinAddr) public view returns (uint) { uint price = getPrice(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); (, uint mat) = Spotter(SPOTTER_ADDRESS).ilks(_ilk); uint maxCollateral = sub(sub(collateral, (div(mul(mat, debt), price))), 10); uint normalizeMaxCollateral = maxCollateral; if (Join(_joinAddr).dec() != 18) { normalizeMaxCollateral = maxCollateral / (10 ** (18 - Join(_joinAddr).dec())); } return normalizeMaxCollateral; } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP /// @dev Substracts 10 wei to aviod rounding error later on function getMaxDebt(uint _cdpId, bytes32 _ilk) public virtual view returns (uint) { uint price = getPrice(_ilk); (, uint mat) = spotter.ilks(_ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(sub(div(mul(collateral, price), mat), debt), 10); } /// @notice Gets a price of the asset /// @param _ilk Ilk of the CDP function getPrice(bytes32 _ilk) public view returns (uint) { (, uint mat) = spotter.ilks(_ilk); (,,uint spot,,) = vat.ilks(_ilk); return rmul(rmul(spot, spotter.par()), mat); } /// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getRatio(uint _cdpId, bytes32 _ilk) public view returns (uint) { uint price = getPrice( _ilk); (uint collateral, uint debt) = getCdpInfo(manager, _cdpId, _ilk); if (debt == 0) return 0; return rdiv(wmul(collateral, price), debt); } /// @notice Gets CDP info (collateral, debt, price, ilk) /// @param _cdpId Id of the CDP function getCdpDetailedInfo(uint _cdpId) public view returns (uint collateral, uint debt, uint price, bytes32 ilk) { address urn = manager.urns(_cdpId); ilk = manager.ilks(_cdpId); (collateral, debt) = vat.urns(ilk, urn); (,uint rate,,,) = vat.ilks(ilk); debt = rmul(debt, rate); price = getPrice(ilk); } } contract MCDSaverTaker is MCDSaverProxy, GasBurner { address payable public constant MCD_SAVER_FLASH_LOAN = 0x28e444b53a9e7E3F6fFe50E93b18dCce7838551F; address public constant AAVE_POOL_CORE = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3; ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); function boostWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxDebt = getMaxDebt(_cdpId, manager.ilks(_cdpId)); if (maxDebt >= _exchangeData.srcAmount) { boost(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxDebt); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, false); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, DAI_ADDRESS, loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } function repayWithLoan( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _gasCost, address _joinAddr ) public payable burnGas(25) { uint256 maxColl = getMaxCollateral(_cdpId, manager.ilks(_cdpId), _joinAddr); if (maxColl >= _exchangeData.srcAmount) { repay(_exchangeData, _cdpId, _gasCost, _joinAddr); return; } MCD_SAVER_FLASH_LOAN.transfer(msg.value); // 0x fee uint256 loanAmount = sub(_exchangeData.srcAmount, maxColl); uint maxLiq = getAvailableLiquidity(_joinAddr); loanAmount = loanAmount > maxLiq ? maxLiq : loanAmount; manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 1); bytes memory paramsData = abi.encode(packExchangeData(_exchangeData), _cdpId, _gasCost, _joinAddr, true); lendingPool.flashLoan(MCD_SAVER_FLASH_LOAN, getAaveCollAddr(_joinAddr), loanAmount, paramsData); manager.cdpAllow(_cdpId, MCD_SAVER_FLASH_LOAN, 0); } /// @notice Gets the maximum amount of debt available to generate /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP function getMaxDebt(uint256 _cdpId, bytes32 _ilk) public override view returns (uint256) { uint256 price = getPrice(_ilk); (, uint256 mat) = spotter.ilks(_ilk); (uint256 collateral, uint256 debt) = getCdpInfo(manager, _cdpId, _ilk); return sub(wdiv(wmul(collateral, price), mat), debt); } function getAaveCollAddr(address _joinAddr) internal view returns (address) { if (_joinAddr == 0x2F0b23f53734252Bda2277357e97e1517d6B042A || _joinAddr == 0x775787933e92b709f2a3C70aa87999696e74A9F8) { return KYBER_ETH_ADDRESS; } else { return getCollateralAddr(_joinAddr); } } function getAvailableLiquidity(address _joinAddr) internal view returns (uint liquidity) { address tokenAddr = getAaveCollAddr(_joinAddr); if (tokenAddr == KYBER_ETH_ADDRESS) { liquidity = AAVE_POOL_CORE.balance; } else { liquidity = ERC20(tokenAddr).balanceOf(AAVE_POOL_CORE); } } function _packData( uint _cdpId, uint _gasCost, address _joinAddr, SaverExchangeCore.ExchangeData memory exchangeData ) internal pure returns (uint[6] memory numData, address[5] memory addrData, bytes memory callData) { numData = [ exchangeData.srcAmount, exchangeData.destAmount, exchangeData.minPrice, exchangeData.price0x, _cdpId, _gasCost ]; addrData = [ exchangeData.srcAddr, exchangeData.destAddr, exchangeData.exchangeAddr, exchangeData.wrapper, _joinAddr ]; callData = exchangeData.callData; } } contract SavingsProxy is DSRSavingsProtocol, CompoundSavingsProtocol { address public constant ADAI_ADDRESS = 0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d; address public constant SAVINGS_DYDX_ADDRESS = 0x03b1565e070df392e48e7a8e01798C4B00E534A5; address public constant SAVINGS_AAVE_ADDRESS = 0x535B9035E9bA8D7efe0FeAEac885fb65b303E37C; address public constant NEW_IDAI_ADDRESS = 0x493C57C4763932315A328269E1ADaD09653B9081; address public constant COMP_ADDRESS = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant SAVINGS_LOGGER_ADDRESS = 0x89b3635BD2bAD145C6f92E82C9e83f06D5654984; address public constant SOLO_MARGIN_ADDRESS = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; enum SavingsProtocol {Compound, Dydx, Fulcrum, Dsr, Aave} function deposit(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrDeposit(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logDeposit(msg.sender, uint8(_protocol), _amount); } function withdraw(SavingsProtocol _protocol, uint256 _amount) public { if (_protocol == SavingsProtocol.Dsr) { dsrWithdraw(_amount, true); } else if (_protocol == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_protocol, _amount, true); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logWithdraw(msg.sender, uint8(_protocol), _amount); } function swap(SavingsProtocol _from, SavingsProtocol _to, uint256 _amount) public { if (_from == SavingsProtocol.Dsr) { dsrWithdraw(_amount, false); } else if (_from == SavingsProtocol.Compound) { compWithdraw(msg.sender, _amount); } else { _withdraw(_from, _amount, false); } // possible to withdraw 1-2 wei less than actual amount due to division precision // so we deposit all amount on DSProxy uint256 amountToDeposit = ERC20(DAI_ADDRESS).balanceOf(address(this)); if (_to == SavingsProtocol.Dsr) { dsrDeposit(amountToDeposit, false); } else if (_from == SavingsProtocol.Compound) { compDeposit(msg.sender, _amount); } else { _deposit(_to, amountToDeposit, false); } SavingsLogger(SAVINGS_LOGGER_ADDRESS).logSwap( msg.sender, uint8(_from), uint8(_to), _amount ); } function withdrawDai() public { ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); } function claimComp() public { ComptrollerInterface(COMP_ADDRESS).claimComp(address(this)); } function getAddress(SavingsProtocol _protocol) public pure returns (address) { if (_protocol == SavingsProtocol.Dydx) { return SAVINGS_DYDX_ADDRESS; } if (_protocol == SavingsProtocol.Aave) { return SAVINGS_AAVE_ADDRESS; } } function _deposit(SavingsProtocol _protocol, uint256 _amount, bool _fromUser) internal { if (_fromUser) { ERC20(DAI_ADDRESS).transferFrom(msg.sender, address(this), _amount); } approveDeposit(_protocol); ProtocolInterface(getAddress(_protocol)).deposit(address(this), _amount); endAction(_protocol); } function _withdraw(SavingsProtocol _protocol, uint256 _amount, bool _toUser) public { approveWithdraw(_protocol); ProtocolInterface(getAddress(_protocol)).withdraw(address(this), _amount); endAction(_protocol); if (_toUser) { withdrawDai(); } } function endAction(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(false); } } function approveDeposit(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound || _protocol == SavingsProtocol.Fulcrum || _protocol == SavingsProtocol.Aave) { ERC20(DAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { ERC20(DAI_ADDRESS).approve(SOLO_MARGIN_ADDRESS, uint256(-1)); setDydxOperator(true); } } function approveWithdraw(SavingsProtocol _protocol) internal { if (_protocol == SavingsProtocol.Compound) { ERC20(NEW_CDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Dydx) { setDydxOperator(true); } if (_protocol == SavingsProtocol.Fulcrum) { ERC20(NEW_IDAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } if (_protocol == SavingsProtocol.Aave) { ERC20(ADAI_ADDRESS).approve(getAddress(_protocol), uint256(-1)); } } function setDydxOperator(bool _trusted) internal { ISoloMargin.OperatorArg[] memory operatorArgs = new ISoloMargin.OperatorArg[](1); operatorArgs[0] = ISoloMargin.OperatorArg({ operator: getAddress(SavingsProtocol.Dydx), trusted: _trusted }); ISoloMargin(SOLO_MARGIN_ADDRESS).setOperators(operatorArgs); } } contract LoanShifterReceiver is SaverExchangeCore, FlashLoanReceiverBase, AdminAuth { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2612Af3A521c2df9EAF28422Ca335b04AdF3ac66); struct ParamData { bytes proxyData1; bytes proxyData2; address proxy; address debtAddr; uint8 protocol1; uint8 protocol2; uint8 swapType; } constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (ParamData memory paramData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); address protocolAddr1 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol1)); address protocolAddr2 = shifterRegistry.getAddr(getNameByProtocol(paramData.protocol2)); // Send Flash loan amount to DSProxy sendToProxy(payable(paramData.proxy), _reserve, _amount); // Execute the Close/Change debt operation DSProxyInterface(paramData.proxy).execute(protocolAddr1, paramData.proxyData1); if (paramData.swapType == 1) { // COLL_SWAP exchangeData.srcAmount = getBalance(exchangeData.srcAddr); (, uint amount) = _sell(exchangeData); sendToProxy(payable(paramData.proxy), exchangeData.destAddr, amount); } else if (paramData.swapType == 2) { // DEBT_SWAP exchangeData.destAmount = (_amount + _fee); _buy(exchangeData); // Send extra to DSProxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, ERC20(exchangeData.srcAddr).balanceOf(address(this))); } else { // NO_SWAP just send tokens to proxy sendToProxy(payable(paramData.proxy), exchangeData.srcAddr, getBalance(exchangeData.srcAddr)); } // Execute the Open operation DSProxyInterface(paramData.proxy).execute(protocolAddr2, paramData.proxyData2); // Repay FL transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (ParamData memory paramData, ExchangeData memory exchangeData) { ( uint[8] memory numData, // collAmount, debtAmount, id1, id2, srcAmount, destAmount, minPrice, price0x address[8] memory addrData, // addrLoan1, addrLoan2, debtAddr1, debtAddr2, srcAddr, destAddr, exchangeAddr, wrapper uint8[3] memory enumData, // fromProtocol, toProtocol, swapType bytes memory callData, address proxy ) = abi.decode(_params, (uint256[8],address[8],uint8[3],bytes,address)); bytes memory proxyData1; bytes memory proxyData2; uint openDebtAmount = (_amount + _fee); if (enumData[0] == 0) { // MAKER FROM proxyData1 = abi.encodeWithSignature("close(uint256,address,uint256,uint256)", numData[2], addrData[0], _amount, numData[0]); } else if(enumData[0] == 1) { // COMPOUND FROM if (enumData[2] == 2) { // DEBT_SWAP proxyData1 = abi.encodeWithSignature("changeDebt(address,address,uint256,uint256)", addrData[2], addrData[3], (_amount + _fee), numData[4]); } else { proxyData1 = abi.encodeWithSignature("close(address,address,uint256,uint256)", addrData[0], addrData[2], numData[0], numData[1]); } } if (enumData[1] == 0) { // MAKER TO proxyData2 = abi.encodeWithSignature("open(uint256,address,uint256)", numData[3], addrData[1], openDebtAmount); } else if(enumData[1] == 1) { // COMPOUND TO if (enumData[2] == 2) { // DEBT_SWAP proxyData2 = abi.encodeWithSignature("repayAll(address)", addrData[3]); } else { proxyData2 = abi.encodeWithSignature("open(address,address,uint256)", addrData[1], addrData[3], openDebtAmount); } } paramData = ParamData({ proxyData1: proxyData1, proxyData2: proxyData2, proxy: proxy, debtAddr: addrData[2], protocol1: enumData[0], protocol2: enumData[1], swapType: enumData[2] }); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: addrData[4], destAddr: addrData[5], srcAmount: numData[4], destAmount: numData[5], minPrice: numData[6], wrapper: addrData[7], exchangeAddr: addrData[6], callData: callData, price0x: numData[7] }); } function sendToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } function getNameByProtocol(uint8 _proto) internal pure returns (string memory) { if (_proto == 0) { return "MCD_SHIFTER"; } else if (_proto == 1) { return "COMP_SHIFTER"; } } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompShifter is CompoundSaverHelper { address public constant COMPTROLLER_ADDR = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; function getWholeDebt(uint _cdpId, address _joinAddr) public virtual returns(uint loanAmount) { return CTokenInterface(_joinAddr).borrowBalanceCurrent(msg.sender); } function close( address _cCollAddr, address _cBorrowAddr, uint _collAmount, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); // payback debt paybackDebt(_debtAmount, _cBorrowAddr, getUnderlyingAddr(_cBorrowAddr), tx.origin); // draw coll if (CTokenInterface(_cBorrowAddr).borrowBalanceCurrent(address(this)) == 0) { uint cTokenBalance = CTokenInterface(_cCollAddr).balanceOf(address(this)); require(CTokenInterface(_cCollAddr).redeem(cTokenBalance) == 0); } else { require(CTokenInterface(_cCollAddr).redeemUnderlying(_collAmount) == 0); } // Send back money to repay FL if (collAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(collAddr).transfer(msg.sender, ERC20(collAddr).balanceOf(address(this))); } } function changeDebt( address _cBorrowAddrOld, address _cBorrowAddrNew, uint _debtAmountOld, uint _debtAmountNew ) public { address borrowAddrNew = getUnderlyingAddr(_cBorrowAddrNew); // payback debt in one token paybackDebt(_debtAmountOld, _cBorrowAddrOld, getUnderlyingAddr(_cBorrowAddrOld), tx.origin); // draw debt in another one borrowCompound(_cBorrowAddrNew, _debtAmountNew); // Send back money to repay FL if (borrowAddrNew == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddrNew).transfer(msg.sender, ERC20(borrowAddrNew).balanceOf(address(this))); } } function open( address _cCollAddr, address _cBorrowAddr, uint _debtAmount ) public { address collAddr = getUnderlyingAddr(_cCollAddr); address borrowAddr = getUnderlyingAddr(_cBorrowAddr); uint collAmount = 0; if (collAddr == ETH_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(collAddr).balanceOf(address(this)); } depositCompound(collAddr, _cCollAddr, collAmount); // draw debt borrowCompound(_cBorrowAddr, _debtAmount); // Send back money to repay FL if (borrowAddr == ETH_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20(borrowAddr).transfer(msg.sender, ERC20(borrowAddr).balanceOf(address(this))); } } function repayAll(address _cTokenAddr) public { address tokenAddr = getUnderlyingAddr(_cTokenAddr); uint amount = ERC20(tokenAddr).balanceOf(address(this)); if (amount != 0) { paybackDebt(amount, _cTokenAddr, tokenAddr, tx.origin); } } function depositCompound(address _tokenAddr, address _cTokenAddr, uint _amount) internal { approveCToken(_tokenAddr, _cTokenAddr); enterMarket(_cTokenAddr); if (_tokenAddr != ETH_ADDRESS) { require(CTokenInterface(_cTokenAddr).mint(_amount) == 0, "mint error"); } else { CEtherInterface(_cTokenAddr).mint{value: _amount}(); } } function borrowCompound(address _cTokenAddr, uint _amount) internal { enterMarket(_cTokenAddr); require(CTokenInterface(_cTokenAddr).borrow(_amount) == 0); } function enterMarket(address _cTokenAddr) public { address[] memory markets = new address[](1); markets[0] = _cTokenAddr; ComptrollerInterface(COMPTROLLER_ADDR).enterMarkets(markets); } } contract McdShifter is MCDSaverProxy { address public constant OPEN_PROXY_ACTIONS = 0x6d0984E80a86f26c0dd564ca0CF74a8E9Da03305; function getLoanAmount(uint _cdpId, address _joinAddr) public view virtual returns(uint loanAmount) { bytes32 ilk = manager.ilks(_cdpId); (, uint rate,,,) = vat.ilks(ilk); (, uint art) = vat.urns(ilk, manager.urns(_cdpId)); uint dai = vat.dai(manager.urns(_cdpId)); uint rad = sub(mul(art, rate), dai); loanAmount = rad / RAY; loanAmount = mul(loanAmount, RAY) < rad ? loanAmount + 1 : loanAmount; } function close( uint _cdpId, address _joinAddr, uint _loanAmount, uint _collateral ) public { address owner = getOwner(manager, _cdpId); bytes32 ilk = manager.ilks(_cdpId); (uint maxColl, ) = getCdpInfo(manager, _cdpId, ilk); // repay dai debt cdp paybackDebt(_cdpId, ilk, _loanAmount, owner); maxColl = _collateral > maxColl ? maxColl : _collateral; // withdraw collateral from cdp drawMaxCollateral(_cdpId, _joinAddr, maxColl); // send back to msg.sender if (_joinAddr == ETH_JOIN_ADDRESS) { msg.sender.transfer(address(this).balance); } else { ERC20 collToken = ERC20(getCollateralAddr(_joinAddr)); collToken.transfer(msg.sender, collToken.balanceOf(address(this))); } } function open( uint _cdpId, address _joinAddr, uint _debtAmount ) public { uint collAmount = 0; if (_joinAddr == ETH_JOIN_ADDRESS) { collAmount = address(this).balance; } else { collAmount = ERC20(address(Join(_joinAddr).gem())).balanceOf(address(this)); } if (_cdpId == 0) { openAndWithdraw(collAmount, _debtAmount, address(this), _joinAddr); } else { // add collateral addCollateral(_cdpId, _joinAddr, collAmount); // draw debt drawDai(_cdpId, manager.ilks(_cdpId), _debtAmount); } // transfer to repay FL ERC20(DAI_ADDRESS).transfer(msg.sender, ERC20(DAI_ADDRESS).balanceOf(address(this))); if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function openAndWithdraw(uint _collAmount, uint _debtAmount, address _proxy, address _joinAddrTo) internal { bytes32 ilk = Join(_joinAddrTo).ilk(); if (_joinAddrTo == ETH_JOIN_ADDRESS) { MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockETHAndDraw{value: address(this).balance}( address(manager), JUG_ADDRESS, ETH_JOIN_ADDRESS, DAI_JOIN_ADDRESS, ilk, _debtAmount, _proxy ); } else { ERC20(getCollateralAddr(_joinAddrTo)).approve(OPEN_PROXY_ACTIONS, uint256(-1)); MCDCreateProxyActions(OPEN_PROXY_ACTIONS).openLockGemAndDraw( address(manager), JUG_ADDRESS, _joinAddrTo, DAI_JOIN_ADDRESS, ilk, _collAmount, _debtAmount, true, _proxy ); } } function drawMaxCollateral(uint _cdpId, address _joinAddr, uint _amount) internal returns (uint) { manager.frob(_cdpId, -toPositiveInt(_amount), 0); manager.flux(_cdpId, address(this), _amount); uint joinAmount = _amount; if (Join(_joinAddr).dec() != 18) { joinAmount = _amount / (10 ** (18 - Join(_joinAddr).dec())); } Join(_joinAddr).exit(address(this), joinAmount); if (_joinAddr == ETH_JOIN_ADDRESS) { Join(_joinAddr).gem().withdraw(joinAmount); // Weth -> Eth } return joinAmount; } } contract AaveSaverProxy is GasBurner, SaverExchangeCore, AaveHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; uint public constant VARIABLE_RATE = 2; function repay(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); address payable user = payable(getUserAddress()); uint256 maxCollateral = getMaxCollateral(_data.srcAddr, address(this)); // don't swap more than maxCollateral _data.srcAmount = _data.srcAmount > maxCollateral ? maxCollateral : _data.srcAmount; // redeem collateral address aTokenCollateral = ILendingPool(lendingPoolCore).getReserveATokenAddress(_data.srcAddr); IAToken(aTokenCollateral).redeem(_data.srcAmount); // swap (, uint256 destAmount) = _sell(_data); destAmount -= getFee(destAmount, user, _gasCost, _data.destAddr); // payback if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).repay{value: destAmount}(_data.destAddr, destAmount, payable(address(this))); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).repay(_data.destAddr, destAmount, payable(address(this))); } // first return 0x fee to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveRepay", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } function boost(ExchangeData memory _data, uint _gasCost) public payable burnGas(20) { address lendingPoolCore = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPoolCore(); address lendingPool = ILendingPoolAddressesProvider(AAVE_LENDING_POOL_ADDRESSES).getLendingPool(); (,,,,,,,,,bool collateralEnabled) = ILendingPool(lendingPool).getUserReserveData(_data.destAddr, address(this)); address payable user = payable(getUserAddress()); uint256 maxBorrow = getMaxBorrow(_data.srcAddr, address(this)); _data.srcAmount = _data.srcAmount > maxBorrow ? maxBorrow : _data.srcAmount; // borrow amount ILendingPool(lendingPool).borrow(_data.srcAddr, _data.srcAmount, VARIABLE_RATE, AAVE_REFERRAL_CODE); _data.srcAmount -= getFee(_data.srcAmount, user, _gasCost, _data.srcAddr); // swap (, uint256 destAmount) = _sell(_data); if (_data.destAddr == ETH_ADDR) { ILendingPool(lendingPool).deposit{value: destAmount}(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } else { approveToken(_data.destAddr, lendingPoolCore); ILendingPool(lendingPool).deposit(_data.destAddr, destAmount, AAVE_REFERRAL_CODE); } if (!collateralEnabled) { ILendingPool(lendingPool).setUserUseReserveAsCollateral(_data.destAddr, true); } // returning to msg.sender as it is the address that actually sent 0x fee sendContractBalance(ETH_ADDR, msg.sender, min(address(this).balance, msg.value)); // send all leftovers from dest addr to proxy owner sendFullContractBalance(_data.destAddr, user); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "AaveBoost", abi.encode(_data.srcAddr, _data.destAddr, _data.srcAmount, destAmount)); } } contract CompoundLoanInfo is CompoundSafetyRatio { struct LoanData { address user; uint128 ratio; address[] collAddr; address[] borrowAddr; uint[] collAmounts; uint[] borrowAmounts; } struct TokenInfo { address cTokenAddress; address underlyingTokenAddress; uint collateralFactor; uint price; } struct TokenInfoFull { address underlyingTokenAddress; uint supplyRate; uint borrowRate; uint exchangeRate; uint marketLiquidity; uint totalSupply; uint totalBorrow; uint collateralFactor; uint price; } address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public constant CETH_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _user Address of the user function getRatio(address _user) public view returns (uint) { // For each asset the account is in return getSafetyRatio(_user); } /// @notice Fetches Compound prices for tokens /// @param _cTokens Arr. of cTokens for which to get the prices /// @return prices Array of prices function getPrices(address[] memory _cTokens) public view returns (uint[] memory prices) { prices = new uint[](_cTokens.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokens.length; ++i) { prices[i] = CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokens[i]); } } /// @notice Fetches Compound collateral factors for tokens /// @param _cTokens Arr. of cTokens for which to get the coll. factors /// @return collFactors Array of coll. factors function getCollFactors(address[] memory _cTokens) public view returns (uint[] memory collFactors) { collFactors = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; ++i) { (, collFactors[i]) = comp.markets(_cTokens[i]); } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _user Address of the user /// @return data LoanData information function getLoanData(address _user) public view returns (LoanData memory data) { address[] memory assets = comp.getAssetsIn(_user); address oracleAddr = comp.oracle(); data = LoanData({ user: _user, ratio: 0, collAddr: new address[](assets.length), borrowAddr: new address[](assets.length), collAmounts: new uint[](assets.length), borrowAmounts: new uint[](assets.length) }); uint collPos = 0; uint borrowPos = 0; for (uint i = 0; i < assets.length; i++) { address asset = assets[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory oraclePrice; if (cTokenBalance != 0 || borrowBalance != 0) { oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)}); } // Sum up collateral in Usd if (cTokenBalance != 0) { Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, Exp memory tokensToUsd) = mulExp(exchangeRate, oraclePrice); data.collAddr[collPos] = asset; (, data.collAmounts[collPos]) = mulScalarTruncate(tokensToUsd, cTokenBalance); collPos++; } // Sum up debt in Usd if (borrowBalance != 0) { data.borrowAddr[borrowPos] = asset; (, data.borrowAmounts[borrowPos]) = mulScalarTruncate(oraclePrice, borrowBalance); borrowPos++; } } data.ratio = uint128(getSafetyRatio(_user)); return data; } function getTokenBalances(address _user, address[] memory _cTokens) public view returns (uint[] memory balances, uint[] memory borrows) { balances = new uint[](_cTokens.length); borrows = new uint[](_cTokens.length); for (uint i = 0; i < _cTokens.length; i++) { address asset = _cTokens[i]; (, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa) = CTokenInterface(asset).getAccountSnapshot(_user); Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa}); (, balances[i]) = mulScalarTruncate(exchangeRate, cTokenBalance); borrows[i] = borrowBalance; } } /// @notice Fetches all the collateral/debt address and amounts, denominated in usd /// @param _users Addresses of the user /// @return loans Array of LoanData information function getLoanDataArr(address[] memory _users) public view returns (LoanData[] memory loans) { loans = new LoanData[](_users.length); for (uint i = 0; i < _users.length; ++i) { loans[i] = getLoanData(_users[i]); } } /// @notice Calcualted the ratio of coll/debt for a compound user /// @param _users Addresses of the user /// @return ratios Array of ratios function getRatios(address[] memory _users) public view returns (uint[] memory ratios) { ratios = new uint[](_users.length); for (uint i = 0; i < _users.length; ++i) { ratios[i] = getSafetyRatio(_users[i]); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfo[] memory tokens) { tokens = new TokenInfo[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); tokens[i] = TokenInfo({ cTokenAddress: _cTokenAddresses[i], underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Information about cTokens /// @param _cTokenAddresses Array of cTokens addresses /// @return tokens Array of cTokens infomartion function getFullTokensInfo(address[] memory _cTokenAddresses) public returns(TokenInfoFull[] memory tokens) { tokens = new TokenInfoFull[](_cTokenAddresses.length); address oracleAddr = comp.oracle(); for (uint i = 0; i < _cTokenAddresses.length; ++i) { (, uint collFactor) = comp.markets(_cTokenAddresses[i]); CTokenInterface cToken = CTokenInterface(_cTokenAddresses[i]); tokens[i] = TokenInfoFull({ underlyingTokenAddress: getUnderlyingAddr(_cTokenAddresses[i]), supplyRate: cToken.supplyRatePerBlock(), borrowRate: cToken.borrowRatePerBlock(), exchangeRate: cToken.exchangeRateCurrent(), marketLiquidity: cToken.getCash(), totalSupply: cToken.totalSupply(), totalBorrow: cToken.totalBorrowsCurrent(), collateralFactor: collFactor, price: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(_cTokenAddresses[i]) }); } } /// @notice Returns the underlying address of the cToken asset /// @param _cTokenAddress cToken address /// @return Token address of the cToken specified function getUnderlyingAddr(address _cTokenAddress) internal returns (address) { if (_cTokenAddress == CETH_ADDRESS) { return ETH_ADDRESS; } else { return CTokenInterface(_cTokenAddress).underlying(); } } } contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab); address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08; address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F; // solhint-disable-next-line no-empty-blocks constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {} /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (address payable proxyAddr, bytes memory proxyData, ExchangeData memory exchangeData) = packFunctionCall(_amount, _fee, _params); // Swap (, uint sellAmount) = _sell(exchangeData); // DFS fee getFee(sellAmount, exchangeData.destAddr, proxyAddr); // Send amount to DSProxy sendToProxy(proxyAddr, exchangeData.destAddr); address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER"); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(compOpenProxy, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { // solhint-disable-next-line avoid-tx-origin tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (address payable, bytes memory proxyData, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper bytes memory callData, address proxy ) = abi.decode(_params, (uint256[4],address[6],bytes,address)); proxyData = abi.encodeWithSignature( "open(address,address,uint256)", cAddresses[0], cAddresses[1], (_amount + _fee)); exchangeData = SaverExchangeCore.ExchangeData({ srcAddr: cAddresses[2], destAddr: cAddresses[3], srcAmount: numData[0], destAmount: numData[1], minPrice: numData[2], wrapper: cAddresses[5], exchangeAddr: cAddresses[4], callData: callData, price0x: numData[3] }); return (payable(proxy), proxyData, exchangeData); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address function sendToProxy(address payable _proxy, address _reserve) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this))); } else { _proxy.transfer(address(this).balance); } } function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) { uint fee = 400; DSProxy proxy = DSProxy(payable(_proxy)); address user = proxy.owner(); if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) { fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user); } feeAmount = (fee == 0) ? 0 : (_amount / fee); // fee can't go over 20% of the whole amount if (feeAmount > (_amount / 5)) { feeAmount = _amount / 5; } if (_tokenAddr == ETH_ADDRESS) { WALLET_ADDR.transfer(feeAmount); } else { ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount); } } // solhint-disable-next-line no-empty-blocks receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundSaverFlashLoan is FlashLoanReceiverBase, SaverExchangeCore { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); address payable public COMPOUND_SAVER_FLASH_PROXY = 0xBcEAb469CbBA225E9dc9Cbd898808A4742687096; address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address public owner; using SafeERC20 for ERC20; constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public { owner = msg.sender; } /// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (bytes memory proxyData, address payable proxyAddr) = packFunctionCall(_amount, _fee, _params); // Send Flash loan amount to DSProxy sendLoanToProxy(proxyAddr, _reserve, _amount); // Execute the DSProxy call DSProxyInterface(proxyAddr).execute(COMPOUND_SAVER_FLASH_PROXY, proxyData); // Repay the loan with the money DSProxy sent back transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } /// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params /// @return proxyData Formated function call data function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (bytes memory proxyData, address payable) { ( bytes memory exDataBytes, address[2] memory cAddresses, // cCollAddress, cBorrowAddress uint256 gasCost, bool isRepay, address payable proxyAddr ) = abi.decode(_params, (bytes,address[2],uint256,bool,address)); ExchangeData memory _exData = unpackExchangeData(exDataBytes); uint[2] memory flashLoanData = [_amount, _fee]; if (isRepay) { proxyData = abi.encodeWithSignature("flashRepay((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } else { proxyData = abi.encodeWithSignature("flashBoost((address,address,uint256,uint256,uint256,address,address,bytes,uint256),address[2],uint256,uint256[2])", _exData, cAddresses, gasCost, flashLoanData); } return (proxyData, proxyAddr); } /// @notice Send the FL funds received to DSProxy /// @param _proxy DSProxy address /// @param _reserve Token address /// @param _amount Amount of tokens function sendLoanToProxy(address payable _proxy, address _reserve, uint _amount) internal { if (_reserve != ETH_ADDRESS) { ERC20(_reserve).safeTransfer(_proxy, _amount); } _proxy.transfer(address(this).balance); } receive() external override(SaverExchangeCore, FlashLoanReceiverBase) payable {} } contract CompoundSaverFlashProxy is SaverExchangeCore, CompoundSaverHelper { address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126; using SafeERC20 for ERC20; /// @notice Repays the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for transaction /// @param _flashLoanData Data about FL [amount, fee] function flashRepay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); // draw max coll require(CTokenInterface(_cAddresses[0]).redeemUnderlying(maxColl) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // swap max coll + loanAmount (,swapAmount) = _sell(_exData); // get fee swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = (maxColl + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // payback debt paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // draw collateral for loanAmount + loanFee require(CTokenInterface(_cAddresses[0]).redeemUnderlying(flashBorrowed) == 0); // repay flash loan returnFlashLoan(collToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Boosts the position and sends tokens back for FL /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction /// @param _flashLoanData Data about FL [amount, fee] function flashBoost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost, uint[2] memory _flashLoanData // amount, fee ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint flashBorrowed = _flashLoanData[0] + _flashLoanData[1]; // borrow max amount uint borrowAmount = getMaxBorrow(_cAddresses[1], address(this)); require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { // get dfs fee borrowAmount -= getFee((borrowAmount + _flashLoanData[0]), user, _gasCost, _cAddresses[1]); _exData.srcAmount = (borrowAmount + _flashLoanData[0]); (,swapAmount) = _sell(_exData); } else { swapAmount = (borrowAmount + _flashLoanData[0]); swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } // deposit swaped collateral depositCollateral(collToken, _cAddresses[0], swapAmount); // borrow token to repay flash loan require(CTokenInterface(_cAddresses[1]).borrow(flashBorrowed) == 0); // repay flash loan returnFlashLoan(borrowToken, flashBorrowed); DefisaverLogger(DEFISAVER_LOGGER).Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Helper method to deposit tokens in Compound /// @param _collToken Token address of the collateral /// @param _cCollToken CToken address of the collateral /// @param _depositAmount Amount to deposit function depositCollateral(address _collToken, address _cCollToken, uint _depositAmount) internal { approveCToken(_collToken, _cCollToken); if (_collToken != ETH_ADDRESS) { require(CTokenInterface(_cCollToken).mint(_depositAmount) == 0); } else { CEtherInterface(_cCollToken).mint{value: _depositAmount}(); // reverts on fail } } /// @notice Returns the tokens/ether to the msg.sender which is the FL contract /// @param _tokenAddr Address of token which we return /// @param _amount Amount to return function returnFlashLoan(address _tokenAddr, uint _amount) internal { if (_tokenAddr != ETH_ADDRESS) { ERC20(_tokenAddr).safeTransfer(msg.sender, _amount); } msg.sender.transfer(address(this).balance); } } contract CompoundSaverProxy is CompoundSaverHelper, SaverExchangeCore { DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); /// @notice Withdraws collateral, converts to borrowed token and repays debt /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function repay( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); uint collAmount = (_exData.srcAmount > maxColl) ? maxColl : _exData.srcAmount; require(CTokenInterface(_cAddresses[0]).redeemUnderlying(collAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { (, swapAmount) = _sell(_exData); swapAmount -= getFee(swapAmount, user, _gasCost, _cAddresses[1]); } else { swapAmount = collAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } paybackDebt(swapAmount, _cAddresses[1], borrowToken, user); // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundRepay", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } /// @notice Borrows token, converts to collateral, and adds to position /// @dev Called through the DSProxy /// @param _exData Exchange data /// @param _cAddresses Coll/Debt addresses [cCollAddress, cBorrowAddress] /// @param _gasCost Gas cost for specific transaction function boost( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable { enterMarket(_cAddresses[0], _cAddresses[1]); address payable user = payable(getUserAddress()); uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); uint borrowAmount = (_exData.srcAmount > maxBorrow) ? maxBorrow : _exData.srcAmount; require(CTokenInterface(_cAddresses[1]).borrow(borrowAmount) == 0); address collToken = getUnderlyingAddr(_cAddresses[0]); address borrowToken = getUnderlyingAddr(_cAddresses[1]); uint swapAmount = 0; if (collToken != borrowToken) { borrowAmount -= getFee(borrowAmount, user, _gasCost, _cAddresses[1]); _exData.srcAmount = borrowAmount; (,swapAmount) = _sell(_exData); } else { swapAmount = borrowAmount; swapAmount -= getGasCost(swapAmount, _gasCost, _cAddresses[1]); } approveCToken(collToken, _cAddresses[0]); if (collToken != ETH_ADDRESS) { require(CTokenInterface(_cAddresses[0]).mint(swapAmount) == 0); } else { CEtherInterface(_cAddresses[0]).mint{value: swapAmount}(); // reverts on fail } // handle 0x fee tx.origin.transfer(address(this).balance); // log amount, collToken, borrowToken logger.Log(address(this), msg.sender, "CompoundBoost", abi.encode(_exData.srcAmount, swapAmount, collToken, borrowToken)); } } contract SaverExchange is SaverExchangeCore, AdminAuth, GasBurner { using SafeERC20 for ERC20; uint256 public constant SERVICE_FEE = 800; // 0.125% Fee // solhint-disable-next-line const-name-snakecase DefisaverLogger public constant logger = DefisaverLogger(0x5c55B921f590a89C1Ebe84dF170E655a82b62126); uint public burnAmount = 10; /// @notice Takes a src amount of tokens and converts it into the dest token /// @dev Takes fee from the _srcAmount before the exchange /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function sell(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount) { // take fee uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint destAmount) = _sell(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeSell", abi.encode(wrapper, exData.srcAddr, exData.destAddr, exData.srcAmount, destAmount)); } /// @notice Takes a dest amount of tokens and converts it from the src token /// @dev Send always more than needed for the swap, extra will be returned /// @param exData [srcAddr, destAddr, srcAmount, destAmount, minPrice, exchangeType, exchangeAddr, callData, price0x] /// @param _user User address who called the exchange function buy(ExchangeData memory exData, address payable _user) public payable burnGas(burnAmount){ uint dfsFee = getFee(exData.srcAmount, exData.srcAddr); exData.srcAmount = sub(exData.srcAmount, dfsFee); // Perform the exchange (address wrapper, uint srcAmount) = _buy(exData); // send back any leftover ether or tokens sendLeftover(exData.srcAddr, exData.destAddr, _user); // log the event logger.Log(address(this), msg.sender, "ExchangeBuy", abi.encode(wrapper, exData.srcAddr, exData.destAddr, srcAmount, exData.destAmount)); } /// @notice Takes a feePercentage and sends it to wallet /// @param _amount Dai amount of the whole trade /// @param _token Address of the token /// @return feeAmount Amount in Dai owner earned on the fee function getFee(uint256 _amount, address _token) internal returns (uint256 feeAmount) { uint256 fee = SERVICE_FEE; if (Discount(DISCOUNT_ADDRESS).isCustomFeeSet(msg.sender)) { fee = Discount(DISCOUNT_ADDRESS).getCustomServiceFee(msg.sender); } if (fee == 0) { feeAmount = 0; } else { feeAmount = _amount / fee; if (_token == KYBER_ETH_ADDRESS) { WALLET_ID.transfer(feeAmount); } else { ERC20(_token).safeTransfer(WALLET_ID, feeAmount); } } } /// @notice Changes the amount of gas token we burn for each call /// @dev Only callable by the owner /// @param _newBurnAmount New amount of gas tokens to be burned function changeBurnAmount(uint _newBurnAmount) public { require(owner == msg.sender); burnAmount = _newBurnAmount; } } contract MCDSaverFlashLoan is MCDSaverProxy, AdminAuth, FlashLoanReceiverBase { ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); constructor() FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) public {} struct SaverData { uint cdpId; uint gasCost; uint loanAmount; uint fee; address joinAddr; } function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { //check the contract has the specified balance require(_amount <= getBalanceInternal(address(this), _reserve), "Invalid balance for the contract"); ( bytes memory exDataBytes, uint cdpId, uint gasCost, address joinAddr, bool isRepay ) = abi.decode(_params, (bytes,uint256,uint256,address,bool)); ExchangeData memory exchangeData = unpackExchangeData(exDataBytes); SaverData memory saverData = SaverData({ cdpId: cdpId, gasCost: gasCost, loanAmount: _amount, fee: _fee, joinAddr: joinAddr }); if (isRepay) { repayWithLoan(exchangeData, saverData); } else { boostWithLoan(exchangeData, saverData); } transferFundsBackToPoolInternal(_reserve, _amount.add(_fee)); // if there is some eth left (0x fee), return it to user if (address(this).balance > 0) { tx.origin.transfer(address(this).balance); } } function boostWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); // Draw users Dai uint maxDebt = getMaxDebt(_saverData.cdpId, manager.ilks(_saverData.cdpId)); uint daiDrawn = drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), maxDebt); // Calc. fees uint dsfFee = getFee((daiDrawn + _saverData.loanAmount), _saverData.gasCost, user); uint afterFee = (daiDrawn + _saverData.loanAmount) - dsfFee; // Swap _exchangeData.srcAmount = afterFee; (, uint swapedAmount) = _sell(_exchangeData); // Return collateral addCollateral(_saverData.cdpId, _saverData.joinAddr, swapedAmount); // Draw Dai to repay the flash loan drawDai(_saverData.cdpId, manager.ilks(_saverData.cdpId), (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashBoost", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } function repayWithLoan( ExchangeData memory _exchangeData, SaverData memory _saverData ) internal { address user = getOwner(manager, _saverData.cdpId); bytes32 ilk = manager.ilks(_saverData.cdpId); // Draw collateral uint maxColl = getMaxCollateral(_saverData.cdpId, ilk, _saverData.joinAddr); uint collDrawn = drawCollateral(_saverData.cdpId, _saverData.joinAddr, maxColl); // Swap _exchangeData.srcAmount = (_saverData.loanAmount + collDrawn); (, uint swapedAmount) = _sell(_exchangeData); uint paybackAmount = (swapedAmount - getFee(swapedAmount, _saverData.gasCost, user)); paybackAmount = limitLoanAmount(_saverData.cdpId, ilk, paybackAmount, user); // Payback the debt paybackDebt(_saverData.cdpId, ilk, paybackAmount, user); // Draw collateral to repay the flash loan drawCollateral(_saverData.cdpId, _saverData.joinAddr, (_saverData.loanAmount + _saverData.fee)); logger.Log(address(this), msg.sender, "MCDFlashRepay", abi.encode(_saverData.cdpId, owner, _exchangeData.srcAmount, swapedAmount)); } /// @notice Handles that the amount is not bigger than cdp debt and not dust function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - debt)); return debt; } uint debtLeft = debt - _paybackAmount; (,,,, uint dust) = vat.ilks(_ilk); dust = dust / 10**27; // Less than dust value if (debtLeft < dust) { uint amountOverDust = (dust - debtLeft); ERC20(DAI_ADDRESS).transfer(_owner, amountOverDust); return (_paybackAmount - amountOverDust); } return _paybackAmount; } receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {} } contract CompoundFlashLoanTaker is CompoundSaverProxy, ProxyPermission, GasBurner { ILendingPool public constant lendingPool = ILendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); address payable public constant COMPOUND_SAVER_FLASH_LOAN = 0x0ed294340b6328647A652207AA72902747C84c94; /// @notice Repays the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function repayWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(25) { uint maxColl = getMaxCollateral(_cAddresses[0], address(this)); if (_exData.srcAmount <= maxColl) { repay(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxColl); bytes memory encoded = packExchangeData(_exData); bytes memory paramsData = abi.encode(encoded, _cAddresses, _gasCost, true, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[0]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashRepay", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[0])); } } /// @notice Boosts the position with it's own fund or with FL if needed /// @param _exData Exchange data /// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress] /// @param _gasCost Gas cost for specific transaction function boostWithLoan( ExchangeData memory _exData, address[2] memory _cAddresses, // cCollAddress, cBorrowAddress uint256 _gasCost ) public payable burnGas(20) { uint maxBorrow = getMaxBorrow(_cAddresses[1], address(this)); if (_exData.srcAmount <= maxBorrow) { boost(_exData, _cAddresses, _gasCost); } else { // 0x fee COMPOUND_SAVER_FLASH_LOAN.transfer(msg.value); uint loanAmount = (_exData.srcAmount - maxBorrow); bytes memory paramsData = abi.encode(packExchangeData(_exData), _cAddresses, _gasCost, false, address(this)); givePermission(COMPOUND_SAVER_FLASH_LOAN); lendingPool.flashLoan(COMPOUND_SAVER_FLASH_LOAN, getUnderlyingAddr(_cAddresses[1]), loanAmount, paramsData); removePermission(COMPOUND_SAVER_FLASH_LOAN); logger.Log(address(this), msg.sender, "CompoundFlashBoost", abi.encode(loanAmount, _exData.srcAmount, _cAddresses[1])); } } }
0x608060405234801561001057600080fd5b50600436106100935760003560e01c806382dfc5f71161006657806382dfc5f7146100e65780638823151b146100ee578063d36b907d146100f6578063e074bb47146100fe578063ef9486df1461011157610093565b8063329b8f591461009857806339df1878146100ad5780633d391f70146100cb5780634d9fb18f146100de575b600080fd5b6100ab6100a63660046109f0565b610119565b005b6100b5610478565b6040516100c29190610bbb565b60405180910390f35b6100ab6100d93660046109d4565b610490565b6100b5610670565b6100b5610688565b6100b56106a0565b6100b56106b8565b6100ab61010c3660046109d4565b6106d0565b6100b561077e565b731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e600061014d73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2610796565b9050600061015a8461079c565b60405163095ea7b360e01b815290915073c02aaa39b223fe8d0a0e5c4f27ead9083c756cc29063095ea7b3906101aa90731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e908590600401610c96565b602060405180830381600087803b1580156101c457600080fd5b505af11580156101d8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101fc9190610a30565b5060408051600380825260808201909252606091816020015b61021d610942565b81526020019060019003908161021557905050905061025183867344e4ef23b4794699d0625657cadcb96e07820ffe6107b5565b8160008151811061025e57fe5b60200260200101819052506102ae8787873330604051602001610285959493929190610c64565b6040516020818303038152906040527344e4ef23b4794699d0625657cadcb96e07820ffe610840565b816001815181106102bb57fe5b60200260200101819052506102d18383306108b2565b816002815181106102de57fe5b6020908102919091010152604080516001808252818301909252606091816020015b610308610994565b8152602001906001900390816103005790505090506103256108ed565b8160008151811061033257fe5b602002602001018190525061035a7344e4ef23b4794699d0625657cadcb96e07820ffe610490565b60405163a67a6a4560e01b81526001600160a01b0386169063a67a6a45906103889084908690600401610caf565b600060405180830381600087803b1580156103a257600080fd5b505af11580156103b6573d6000803e3d6000fd5b505050506103d77344e4ef23b4794699d0625657cadcb96e07820ffe6106d0565b735c55b921f590a89c1ebe84df170e655a82b621266001600160a01b031663d061ce5030338b8b60405160200161040f929190610bcf565b6040516020818303038152906040526040518463ffffffff1660e01b815260040161043c93929190610be9565b600060405180830381600087803b15801561045657600080fd5b505af115801561046a573d6000803e3d6000fd5b505050505050505050505050565b735c55b921f590a89c1ebe84df170e655a82b6212681565b6000306001600160a01b031663bf7e214f6040518163ffffffff1660e01b815260040160206040518083038186803b1580156104cb57600080fd5b505afa1580156104df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105039190610a50565b9050806001600160a01b0381166105f457735a15566417e6c1c9546523066500bddbc53f88c76001600160a01b03166365688cc96040518163ffffffff1660e01b8152600401602060405180830381600087803b15801561056357600080fd5b505af1158015610577573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061059b9190610a50565b604051637a9e5e4b60e01b81529091503090637a9e5e4b906105c1908490600401610bbb565b600060405180830381600087803b1580156105db57600080fd5b505af11580156105ef573d6000803e3d6000fd5b505050505b806001600160a01b031663cbeea68c843060405161061190610b99565b6040519081900381206001600160e01b031960e086901b168252610639939291600401610c37565b600060405180830381600087803b15801561065357600080fd5b505af1158015610667573d6000803e3d6000fd5b50505050505050565b7344e4ef23b4794699d0625657cadcb96e07820ffe81565b73c02aaa39b223fe8d0a0e5c4f27ead9083c756cc281565b735a15566417e6c1c9546523066500bddbc53f88c781565b731e0447b19bb6ecfdae1e4ae1694b0c3659614e4e81565b6000306001600160a01b031663bf7e214f6040518163ffffffff1660e01b815260040160206040518083038186803b15801561070b57600080fd5b505afa15801561071f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107439190610a50565b90506001600160a01b038116610759575061077b565b6000819050806001600160a01b0316632bc3217d843060405161061190610b99565b50565b734678f0a6958e4d2bc4f1baf7bc52e8f3564f3fe481565b50600090565b60006107af82600263ffffffff61090d16565b92915050565b6107bd610942565b604080516101008101825260018152600060208083018290528351608081018552828152929384019291908201905b81526020016000815260200186815250815260200185815260200160008152602001836001600160a01b03168152602001600081526020016040518060200160405280600081525081525090509392505050565b610848610942565b50604080516101008101825260088152600060208083018290528351608080820186528382529181018390528085018390526060808201849052948401529282018190529181018290526001600160a01b0390921660a083015260c082015260e081019190915290565b6108ba610942565b604080516101008101825260008082526020808301829052835160808101855260018152929384019291908201906107ec565b6108f5610994565b50604080518082019091523081526001602082015290565b60008282018381101561093b5760405162461bcd60e51b815260040161093290610d4d565b60405180910390fd5b9392505050565b6040805161010081018252600080825260208201529081016109626109ab565b8152602001600081526020016000815260200160006001600160a01b0316815260200160008152602001606081525090565b604080518082019091526000808252602082015290565b604080516080810190915260008082526020820190815260200160008152602001600081525090565b6000602082840312156109e5578081fd5b813561093b81610d8e565b600080600060608486031215610a04578182fd5b8335610a0f81610d8e565b92506020840135610a1f81610d8e565b929592945050506040919091013590565b600060208284031215610a41578081fd5b8151801515811461093b578182fd5b600060208284031215610a61578081fd5b815161093b81610d8e565b6001600160a01b03169052565b60008151808452815b81811015610a9e57602081850181015186830182015201610a82565b81811115610aaf5782602083870101525b50601f01601f19169290920160200192915050565b6000610160825160098110610ad557fe5b80855250602083015160208501526040830151610af56040860182610b4a565b50606083015160c0850152608083015160e085015260a0830151610b1d610100860182610a6c565b5060c083015161012085015260e083015181610140860152610b4182860182610a79565b95945050505050565b8051151582526020810151610b5e81610d84565b60208301526040810151610b7181610d84565b6040830152606090810151910152565b80516001600160a01b03168252602090810151910152565b756578656375746528616464726573732c62797465732960501b815260160190565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b03848116825283166020820152608060408201819052600a908201526910585d99525b5c1bdc9d60b21b60a082015260c060608201819052600090610b4190830184610a79565b6001600160a01b0393841681529190921660208201526001600160e01b0319909116604082015260600190565b6001600160a01b0395861681529385166020850152604084019290925283166060830152909116608082015260a00190565b6001600160a01b03929092168252602082015260400190565b60408082528351828201819052600091906020906060850190828801855b82811015610cf057610ce0848351610b81565b9285019290840190600101610ccd565b505050848103828601528551808252828201935080830282018301878401865b83811015610d3e57601f19858403018752610d2c838351610ac4565b96860196925090850190600101610d10565b50909998505050505050505050565b6020808252601b908201527f536166654d6174683a206164646974696f6e206f766572666c6f770000000000604082015260600190565b6002811061077b57fe5b6001600160a01b038116811461077b57600080fdfea2646970667358221220723fdb7df067fa248e5d1978348391492ed7ab972f2c27f6e96307f52fd0af5c64736f6c63430006060033
[ 37, 17, 11, 8, 9, 12, 16, 5, 2 ]